python 线程小练习

"""
                    _ooOoo_
                   o8888888o
                   88" . "88
                   (| -_- |)
                    O = /O
                ____/`---'\____
              .   ' \| |// `.
               / \||| : |||// 
             / _||||| -:- |||||- 
               | | \ - /// | |
             | \_| ''---/'' | |
               .-\__ `-` ___/-. /
           ___`. .' /--.-- `. . __
        ."" '< `.___\_<|>_/___.' >'"".
       | | : `- \`.;` _ /`;.`/ - ` : | |
           `-. \_ __ /__ _/ .-` / /
  ======`-.____`-.___\_____/___.-`____.-'======
                    `=---='
 .............................................
                      no no no BUG
                      
# -*- coding: utf-8 -*-
# @Author  : nanyu
# @File    : 666.py
# @Time    : 2019/1/4 10:10
# @Software: PyCharm
"""
import _thread  # 使用_thread 模块 start_new_thread 方法新建线程
import time
import pdb


NUM = 0


def print_time(thread_name, delay):
    count = 0
    while count < 10:
        time.sleep(delay)
        count += 1
        print("%s:%s" % (thread_name, time.ctime(time.time())))
    global NUM
    NUM += count


try:
    _thread.start_new_thread(print_time, ('thread-1', 1))  # 1.线程函数2.传递给线程函数的参数必须是元祖
    _thread.start_new_thread(print_time, ('thread-2', 3))
except Exception as e:
    print('Error: %s 启动线程失败' % e)
while NUM < 20:
    pass
print('线程执行完毕!')


"""#线程结束一般靠线程函数自然结束;也可以在线程函数中调用 thread.exit()使抛出异常来结束线程"""


"""
Python通过两个标准库thread和threading提供对线程的支持。thread提供了低级别的、原始的线程以及一个简单的锁。

threading 模块提供的其他方法:

threading.currentThread(): 返回当前的线程变量。
threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了以下方法:

run(): 用以表示线程活动的方法。
start():启动线程活动。
join([time]): 等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
isAlive(): 返回线程是否活动的。
getName(): 返回线程名。
setName(): 设置线程名。
"""
"""
                    _ooOoo_
                   o8888888o
                   88"   "88
                   (| ^_^ |)
                    O = /O
                ____/`---'\____
              .   ' \| |// `.
               / \||| : |||// 
             / _||||| -:- |||||- 
               | | \ - /// | |
             | \_| ''---/'' | |
               .-\__ `-` ___/-. /
           ___`. .' /--.-- `. . __
        ."" '< `.___\_<|>_/___.' >'"".
       | | : `- \`.;` _ /`;.`/ - ` : | |
           `-. \_ __ /__ _/ .-` / /
  ======`-.____`-.___\_____/___.-`____.-'======
                    `=---='
 .............................................
                      no no no BUG
                      
# -*- coding: utf-8 -*-
# @Author  : nanyu
# @File    : 777.py
# @Time    : 2019/1/4 11:39
# @Software: PyCharm
"""
import threading
import time


class MyThread (threading.Thread):  # 继承父类 threading.Thread
    def __init__(self, thread_id, name, counter):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name
        self.counter = counter

    def run(self):  # 执行函数
        print('Starting' + self.name, self.thread_id)
        print_time(self.name, self.counter, 5)
        print('Exiting' + self.name, self.thread_id)


def print_time(thread_name, delay, counter):  # #逻辑函数
    while counter:
        time.sleep(delay)
        print('%s %s' % (thread_name, time.ctime(time.time())))
        counter -= 1


# 创建新线程
thread1 = MyThread(1, 'thread-1', 1)
thread2 = MyThread(2, 'thread-2', 2)

# 开启线程
thread1.start()
thread2.start()


# ============================++++++++++++++++++===================================


import threading
import time

counter = 0
counter_lock = threading.Lock()  # 只是定义一个锁,并不是给资源加锁,你可以定义多个锁,像下两行代码,当你需要占用这个资源时,任何一个锁都可以锁这个资源
counter_lock2 = threading.Lock()
counter_lock3 = threading.Lock()


class YourThread(threading.Thread):
    def __init__(self, thread_id, name, counter):
        threading.Thread.__init__(self)
        self.thread_id = thread_id
        self.name = name
        self.counter = counter

    def run(self):
        print('Starting' + self.name, self.thread_id)
        mutex.acquire(20)  # 获得锁
        print_time(self.name, self.counter, 5)
        mutex.release()  # 使用完counter资源必须要将这个锁打开,让其他线程使用
        print('Exiting' + self.name, self.thread_id)


def print_time(thread_name, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s : %s" % (thread_name, time.ctime(time.time())))
        counter -= 1


mutex = threading.Lock()
threads = []

# 创建新线程
thread1 = YourThread(1, 'thread-1', 1)
thread2 = YourThread(2, 'thread-2', 2)

# 开启新线程
thread1.start()
thread2.start()

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()
print('阻塞等待所有线程结束')
原文地址:https://www.cnblogs.com/nanyu/p/10220407.html