创建两个线程th1,th2当线程th2执行到i==5的时候,线程th1处于等待h2执行完后执行。
import threading
import time
class thread1(threading.Thread):
def __init__ (self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
for i in range(10):
print(self.name, i)
time.sleep(1)
class thread2(threading.Thread):
def __init__ (self, threadname):
threading.Thread.__init__(self, name = threadname)
def run(self):
for i in range(10,20):
print(self.name, i)
time.sleep(1)
if i == 15:
th1.join()
if __name__ == "__main__":
th1 = thread1("thread1")
th2 = thread2("thread2")
th2.start()
th1.start()
显示当前运行的线程名
running = threading.currentThread()
print(running.name)
获得当前所有活动对象
threadlist = threading.enumerate()
for thrname in threadlist:
print(thrname)
活动列表的长度
threadcount = threading.activeCount()
查看一个线程对象的状态,返回1 表示 "runnable" , 否则为表示“dead”
threadflag = threading.isAlive()
生产者与消费者
from queue import Queue
import threading
import random
import time
class producer(threading.Thread):
def __init__ (self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print(self.name, 'adding',i,'to queue')
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print(self.name, 'finished')
class Consumer(threading.Thread):
def __init__ (self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print(self.name, 'got a value', self.sharedata.get())
time.sleep(random.randrange(10)/10.0)
print(self.name, 'finished')
if __name__ == "__main__":
queue = Queue()
producer = producer('producer', queue)
consumer = Consumer('Consumer', queue)
print('starting threads')
producer.start()
consumer.start()
producer.join()
consumer.join()