首页 > 编程语言 > 详细

python - threading

时间:2017-10-24 23:56:52      阅读:317      评论:0      收藏:0      [点我收藏+]
线程的使用书写示例:
(1)
import threading
import time

def run(str1):
print("task:", str1)
time.sleep(5)
for i in range (30):
t1 = threading.Thread(target= run ,args=("abc",))
t2 = threading.Thread(target= run ,args=("cdef",))

t1.start()
t2.start()


(2)
import threading
import time

def run(str1):
print("task:", str1)
time.sleep(5)
   print("task done :",str1)
start_time=time.time()
for i in range (300):
t1 = threading.Thread(target= run ,args=("str_%s"%i,))
t1.start()

print("cost:",time.time()-start_time)#cost: 0.03604459762573242

(3)
import  threading
import time
class MyThreading(threading.Thread ):
def __init__(self,name):
super(MyThreading,self).__init__()
self.name = name
def run(self): #必须要写成run函数
print("姓名:",self.name)
time.sleep(5)
t1 = MyThreading("张三")
t2 = MyThreading("李四")
t1.start()
t2.start()

(4)
import  threading
import time
class MyThreading(threading.Thread ):
def __init__(self,name,sleep_time):
super(MyThreading,self).__init__()
self.name = name
self.sleep_time=sleep_time
def run(self):
print("姓名:",self.name)
time.sleep(self.sleep_time)
print("task done...",self.name)
t1 = MyThreading("张三",2)
t2 = MyThreading("李四",4)
t1.start()
t2.start()
t1.join()
print("main threading ......")

"""
result:
姓名: 张三
姓名: 李四
task done... 张三
main threading ......
task done... 李四
"""

python - threading

原文:http://www.cnblogs.com/xiesongyou/p/7725453.html

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