Java is suitable for multi-threaded programming, and python is suitable for multi-process programming. Because python's multi-threaded underlying logic has synchronization locks, the concurrency effect is not good. Python's multi-processes can take advantage of the computing advantages of multi-core CPUs for concurrency, so tasks that focus on CPU calculations use multi-processes, and tasks that focus on a large number of IO reads and writes use multi-threads.
from threading import Thread
import time
def work(a,b): #多线程需要执行的任务
print(a,b)
time.sleep(3)
threads=[] #存储多线程的列表
for i in range(3): #创建三个线程
th=Thread(target=work,name=i,args=('ABCD','abcd')) #target需要执行的任务,name线程名字,args任务所需要传的参数
threads.append(th) #将产生的线程存入列表中
for i in threads:
i.start() #启动创建的三个线程
for i in threads:
i.join() #等待多线程执行完毕后,再执行下面的代码
print('主进程执行完毕')
One thread calls another thread
import threading
import time
def work2(th):
print('线程2启动')
time.sleep(1)
th.start() #启动线程1
th.join() #等待线程1执行完毕
print('线程2结束')
def work1():
print('线程1启动')
time.sleep(1)
print('线程1结束')
time.sleep(1)
th1=threading.Thread(target=work1) #线程1
th2=threading.Thread(target=work2,args=(th1,)) #线程2,其中将线程1作为参数传到work2函数中
th2.start() #启动线程2
th2.join() #等待线程2执行完毕
print('程序执行完毕')
Daemon thread
import threading
import time
def work():
print('子线程开始')
time.sleep(3)
print('子线程结束')
th=threading.Thread(target=work)
th.setDaemon(True) #将子线程设置为守护线程(当主线程执行完成后,子线程无论是否执行完成都停止执行)
th.start()
print('程序结束----------------')
Usage of thread pool
import time
from multiprocessing.dummy import Pool
def work(a):
time.sleep(a)
print(a,'线程开始执行')
time.sleep(a+7)
print(a,'线程执行完毕')
list=[1,2,3,4,5,6,7,8]
ths=Pool(8) #创建10个容量的线程池
ths.map(work,list) #用线程池执行函数,将列表中的值依次传入线程执行的函数中
ths.close()
ths.join()
print('程序执行完毕')
The use of multi-threaded locks
import threading
import time
data=0 #公共变量,多个线程可操作该变量
lock=threading.Lock() #创建一个锁
def work():
global data
print(threading.currentThread().getName(),'启动')
if lock.acquire(): #哪个线程先执行到这里,哪个线程就先拿到锁,其他线程必须等待该线程释放锁才能继续执行
print(threading.currentThread().getName(),'获得锁')
data+=1 #运用线程锁是为了防止多个线程同时操作该变量时出错
print('data=',data)
time.sleep(2)
print(threading.currentThread().getName(),'释放锁')
lock.release() #释放锁
th1=threading.Thread(target=work)
th2=threading.Thread(target=work)
th3=threading.Thread(target=work)
th1.start()
th2.start()
th3.start()
th1.join()
th2.join()
th3.join()
print('程序结束')