python 多线程DEMO
2020-03-17
python
1474
import threading import queue import time, random thread_queue = queue.Queue() def run_app(params): print("执行程序参数:") print(params) time.sleep(random.randrange(1, 5)) class RunThread(threading.Thread): def __init__(self, thread_name): threading.Thread.__init__(self) self.thread_name = thread_name def run(self): global thread_queue print("线程 %s : 开始" % self.thread_name) while thread_queue.empty() is False: params = thread_queue.get() print("%s: %s" % (self.thread_name, str(params))) run_app(params) print("线程 %s : 结束" % self.thread_name) def init_thread(): global thread_queue thread_limit = 10 task_len = 5 g_start = time.time() tasks = range(task_len) # 多线程 处理 for index in range(task_len): thread_queue.put(tasks[index]) print("即将开启 %d 个 线程执行该任务" % thread_limit) threads = [] for index in range(thread_limit): if index >= task_len: break mythread = RunThread("查询线程:%d" % index) threads.append(mythread) for mythread in threads: mythread.setDaemon(True) mythread.start() for mythread in threads: mythread.join() print("查询耗时:%s 秒" % (round(time.time() - g_start, 2))) if __name__ == "__main__": init_thread()
很赞哦! (0)
相关文章
文章评论
-
-
-
0条评论