仅作为笔记使用
线程:
import threading
import time
import random
def task_thread(counter):
sum = random.randint(1,10)
time.sleep(sum)
print(str(sum)+f'----线程名称:{threading.current_thread().name} 参数:{counter} 开始时间:{time.strftime("%Y-%m-%d %H:%M:%S")}')
#开1000个线程运行task_thread函数,将i作为参数传递给task_thread函数
for i in range(1000):
print('线程-1-'+str(i))
t = threading.Thread(target=task_thread,args=(i,))
t.start()
print('线程-2-'+str(i))
线程池
import time
from concurrent.futures.thread import ThreadPoolExecutor
def task_thread(id):
time.sleep(1)
print(id)
data=[1,2,3,4,5,6,7,8,9]
# 创建一个包含3个线程的线程池
thread_pool = ThreadPoolExecutor(max_workers=3)
#以map的方式提交线程,map可以提交数组数据
thread_pool.map(task_thread,data)
#2.以submit方式提交线程,submit只能提交单个的数据
# for i in data:
# print(i)
# thread_pool.submit(task_thread,i)
线程锁
import threading
mutex = threading.Lock()#执行函数之前添加线程锁
mutex.release()#函数执行后释放线程锁