python 多线程

创建两个线程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()
    
    


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值