线程的使用书写示例:
(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... 李四
"""
守护线程:
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.setDaemon(True) #守护线程
t1.start()
print("-------------task has finished-------------")
print("cost:",time.time()-start_time)#cost: 0.03604459762573242
线程锁示例(Python3以上不须用线程锁)
import threading
num = 0
lock=threading.Lock()
def run():
lock.acquire()
global num
num += 1
lock.release()
for i in range(100):
t=threading.Thread(target=run)
t.start()
print("num:",num)