首页 > 编程语言 > 详细

多线程

时间:2017-11-25 19:52:02      阅读:294      评论:0      收藏:0      [点我收藏+]

多线程

1、简单例子:

  

import threading
import time

def work(n):
time.sleep(2)
print ("threading :",n)

time1 = time.time()

t1 = threading.Thread(target=work,args=("alex",))
t2 = threading.Thread(target=work,args = ("kaka",))
t1.start()
t2.start()
time2 = time.time()
print (time2 - time1)

2、用类实现:
class MyThread(threading.Thread):
def __init__(self,n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print ("run",self.n)

a = MyThread("kaka")
b = MyThread("wawa")

a.run()
b.run()
--------------------------------------------------------------
3、主线程启动子线程,子线程独立运行(由原串行变为并行);
import threading
import time

def work(n):
time.sleep(2)
print ("threading :",n)
start_time = time.time()
for i in range(50):
t = threading.Thread(target=work,args = ("threading %s" % i,))
t.start()
cost = time.time()-start_time
print ("耗时%s" % cost)

4、join()
import threading
import time

def work(n):
print ("threading %s is start!" % n)
time.sleep(2)
print ("threading %s is done!:" % n)
start_time = time.time()
res_list = []
for i in range(50):
t = threading.Thread(target=work,args = ("threading %s" % i,))
t.start()
res_list.append(t)
for t in res_list:#join相当于wait的意思;等待所有线程结束后,再往下走;
t.join()
cost = time.time()-start_time
print ("耗时%s" % cost)

5、
 
 
 

多线程

原文:http://www.cnblogs.com/wulafuer/p/7896100.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!