2017-10-22 回答
python支持多线程效果还不错,很多方面都用到了python 多线程的知识,我前段时间用python 多线程写了个处理生产者和消费者的问题,把代码贴出来给你看下:
#encoding=utf-8
import threading
import random
import time
from queue import queue
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.getname(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getname(),'finished'
# consumer thread
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.getname(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getname(),'finished'
# main thread
def main():
queue = queue()
producer = producer('producer', queue)
consumer = consumer('consumer', queue)
print 'starting threads ...'
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'all threads have terminated.'
if __name__ == '__main__':
main()
如果你想要了解更多的python 多线程知识可以点下面的参考资料的地址,希望对有帮助!