导入包
import threading
- 定义多线程:
- 线程1=threading . Thread(target=函数名,name = ‘线程名字’,arsg=(参数1,参数2))-
- 启动线程:
- 线程1.start()
def job1():
print('T1 start\n')
for i in range(10):
time.sleep(0.1)
print('T1 finish\n')
def main():
thread_job1= threading.Thread(target=job1,name='T1')#创建一个多线程
thread_job1.start()#激活一个多线
print(threading.active_count()) #线程的数量
print('*'*59)
print(threading.enumerate())
print('*'*59)
print(threading.current_thread()) #运行的是哪个线程
#结果
T1 start
3
***********************************************************
[<_MainThread(MainThread, started 12988)>, <Thread(SockThread, started daemon 12280)>, <Thread(T1, started 18520)>]
***********************************************************
<_MainThread(MainThread, started 12988)>
T1 finish
- 想要该线程结束之后再运行下面的程序
- 线程1.join()
def main():
thread_job1= threading.Thread(target=job1,name='T1')#创建一个多线程
thread_job1.start()#激活一个多线
print(threading.active_count()) #线程的数量
print('*'*59)
print(threading.enumerate())
print('*'*59)
print(threading.current_thread()) #运行的是哪个线程
#结果
T1.start
T1.finish
2
***********************************************************
[<_MainThread(MainThread, started 11520)>, <Thread(SockThread, started daemon 21124)>]
***********************************************************
<_MainThread(MainThread, started 11520)>
- 两个自定义线程
def thread_job():
print('T1 start\n')
for i in range(10):
time.sleep(0.1)
print('T1 finish\n')
def thread_jo2():
print('T2 start\n')
print('T2 finish\n')
def main():
thread_job1= threading.Thread(target=thread_job,name='T1')#创建一个多线程
thread_job2=threading.Thread(target=thread_jo2,name='T2')
thread_job1.start()#激活一个多线程
thread_job2.start()
thread_job1.join()#join 之后的语句必须等到Join结束才可以运行
print(threading.active_count()) #线程的数量
print('*'*59)
print(threading.enumerate())
print('*'*59)
print(threading.current_thread()) #运行的是哪个线程
因为多线程没有返回值,所以要先把返回值放在队列
import threading
import time
from queue import Queue
def job1(l,q):
for i in range(len(l)):
l[i]=l[i]**2
q.put(l) # 把处理后的结果放在队列里
def main():
q = Queue() #创建一个队列
threads=[]
data=[[1,2,3],[2,3,4],[3,4,5],[4,5,6]]
results=[]
for i in range(4):
t = threading.Thread(target=job1,args=(data[i],q)) #args传参
t.start()
threads.append(t)
for t in threads:
t.join()
for i in range(4):
results.append(q.get()) #把队列的值放在results中
print(results)
多线程上锁
def job1():
global A,lock
lock.acquire()
for i in range(5):
A+=1
print('job1',A)
lock.release()
def job2():
global A,lock
lock.acquire()
for i in range(5):
A += 10
print('job2',A)
lock.release()
def main():
A = 0
lock = threading.Lock()
t1=threading.Thread(target=job1)
t2=threading.Thread(target=job2)
t1.start()
t2.start()
t1.join()
t2.join()
来源:CSDN
作者:今天@好日子
链接:https://blog.csdn.net/qq_46244390/article/details/104650703