创建线程池,并进行调用 
时间: 2023-05-31 22:06:02 浏览: 19
以下是一个基本的线程池实现示例:
```python
import threading
import queue
class ThreadPool:
def __init__(self, num_threads):
self.task_queue = queue.Queue()
self.threads = []
for i in range(num_threads):
self.threads.append(threading.Thread(target=self.worker_thread))
def start(self):
for thread in self.threads:
thread.start()
def stop(self):
for i in range(len(self.threads)):
self.task_queue.put(None)
for thread in self.threads:
thread.join()
def submit(self, task):
self.task_queue.put(task)
def worker_thread(self):
while True:
task = self.task_queue.get()
if task is None:
break
task()
```
使用示例:
```python
def print_hello():
print("Hello from thread {}".format(threading.current_thread().name))
pool = ThreadPool(4)
pool.start()
for i in range(10):
pool.submit(print_hello)
pool.stop()
```
输出:
```
Hello from thread Thread-1
Hello from thread Thread-3
Hello from thread Thread-2
Hello from thread Thread-4
Hello from thread Thread-1
Hello from thread Thread-3
Hello from thread Thread-2
Hello from thread Thread-4
Hello from thread Thread-1
Hello from thread Thread-3
```
相关推荐


















