创建一个线程
1.示例代码
import time
import threading
def task(arg):
time.sleep(2)
while True:
num = input('>>>')
t = threading.Thread(target=task.args=(num,))
t.start()
创建一个线程池
1.示例代码
import time
from concurrent.futures import ThreadPoolExecutor
def task(m, n):
time.sleep(2)
print(m, n)
# 创建了一个线程池(最多5个线程)
pool = ThreadPoolExecutor(3)
for i in range(10):
# 去线程池中申请一个线程,让线程执行task函数
pool.submit(task, i, 8)
2.示例代码
import time
from concurrent.futures import ThreadPoolExecutor
def task(arg):
time.sleep(50)
pool = ThreadPoolExecutor(10)
while 1:
num = input('>>>')
pool.submit(task,num)