0x00 实现方式
实例化一个Thread对象
from threading import Thread,current_thread
def loop():
for i in range(5):
print(current_thread().name+'第{}次'.format(str(i)))
threadA = Thread(target=loop, name="线程A")
threadB = Thread(target=loop, name="线程B")
threadA.start()
threadB.start()
----------------------------------------------------------------------------------------------------
线程A第0次
线程A第1次
线程B第0次
线程B第1次
线程B第2次
线程B第3次
线程B第4次
线程A第2次
线程A第3次
线程A第4次
继承Thread类,使用init(self)
方法进行初始化,在run(self)
方法中写上该线程要执行的程序
from threading import Thread,current_thread
class MyThread(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
for i in range(5):
print(current_thread().name+'第{}次'.format(str(i)))
threadA = MyThread("线程A")
threadB = MyThread("线程B")
threadA.start()
threadB.start()
----------------------------------------------------------------------------------------------------
线程A第0次
线程A第1次
线程A第2次
线程B第0次
线程B第1次
线程B第2次
线程B第3次
线程B第4次
线程A第3次
线程A第4次
线程锁
from threading import Thread,Lock
lock = Lock()
lock.acquire()
try:
pass
finally:
lock.release() #改写
----------------------------------------------------------------------------------------------------
from threading import Thread,current_thread,Lock
def loop():
lock = Lock()
lock.acquire()
try:
for i in range(5):
print(current_thread().name+'第{}次'.format(str(i)))
finally:
lock.release()
threadA = Thread(target=loop, name="线程A")
threadB = Thread(target=loop, name="线程B")
threadA.start()
threadB.start()
from threading import Thread,Lock
lock = Lock()
with lock:
pass #改写
----------------------------------------------------------------------------------------------------
from threading import Thread,current_thread,Lock
lock = Lock()
class MyThread(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
with lock:
for i in range(5):
print(current_thread().name+'第{}次'.format(str(i)))
threadA = MyThread("线程A")
threadB = MyThread("线程B")
threadA.start()
threadB.start()
Queue
from queue import Queue
q = Queue()
q.put('test')
q.get()
----------------------------------------------------------------------------------------------------
from queue import Queue
from threading import Thread
def Sqare(i):
value=i**2
q.put(value)
def main():
Threads = []
data=[1,2,3,4,5]
for i in data:
thread=Thread(target=Sqare,args=(i,))
thread.start()
Threads.append(thread)
for thread in Threads:
thread.join()
results=[]
for i in range(len(data)):
results.append(q.get())
print(results)
if __name__ == '__main__':
q = Queue()
main()