time.sleep(delay) print(f"Thread {name}: Task {i} complete") # 创建两个线程 thread1 = threading.Thread(target=worker_thread, args=("A", 1)) thread2 = threading.Thread(target=worker_thread, args=("B", 2)) # 启动线程
一、公共代码 首先先贴上一些公共代码,下面的例子都基于这份公共代码运行(注:替换xxx的内容) import time import threading from concurrent.futures import ThreadPoolExecutor def worker(name): print('%s start...' % name) time.sleep(2) print('%s done.' % name) def xxx(): pass if __name__ ==...
from threading import Thread from time import sleep a = 1 # 线程函数 def music(): for i in range(3): sleep(2) print('播放:黄河大合唱 %s' % os.getpid()) global a print("a,",a) a = 1000 # 创建线程对象 t = Thread(target=music) # 启动线程 t.start() for i in range(3): ...
thread = threading.Thread(target=worker, name=f'Worker-{i}') threads.append(thread) thread.start() # 等待所有线程完成 for thread in threads: thread.join() print('All threads completed') ``` 在这个示例中,每个线程在开始执行后都会休眠2秒,然后再继续执行。通过使用 `time.sleep()`,可以轻松地...
time.sleep(10)# 等待10秒后继续执行下一次任务 上面的代码会每隔10秒执行一次print函数。 2. 使用Thread.sleep()函数 如果想要在多线程环境下实现定时任务,可以使用Thread类的sleep()方法。该方法与time.sleep()函数使用方法类似。 importthreadingdeftask():print("执行定时任务")whileTrue: ...
创建一个线程类或使用threading.Thread类。 创建线程实例并传入目标函数。 启动线程。 二、线程睡眠 线程睡眠是指让当前线程暂停执行一段时间,通常用于控制线程的执行节奏或避免频繁的资源争夺。Python提供了time.sleep()函数来实现线程睡眠。 2.1time.sleep()函数 ...
threads.append(thread) thread.start() time.sleep(5) # 主线程休眠5秒 # 通知所有线程继续执行 with condition: condition.notify_all() # 等待所有线程完成 for thread in threads: thread.join() print('All threads completed') ``` 在这个示例中,所有线程在开始执行后都会等待条件变量,直到主线程休眠5秒...
threads.append(thread) thread.start() time.sleep(5) # 主线程休眠5秒 # 通知所有线程继续执行 with condition: condition.notify_all() # 等待所有线程完成 for thread in threads: thread.join() print('All threads completed') ``` 在这个示例中,所有线程在开始执行后都会等待条件变量,直到主线程休眠5秒...
with task_lock:if task_done.value == 10:break time.sleep(1) print("All tasks are done.")if __name__ == "__main__":# 启动监控线程 t = threading.Thread(target=monitor) t.start()# 启动任务1线程for i in range(5): t = threading.Thread(target=worker1, args=(i,...
仍以前⾯章节创建的 thread 线程为例,下⾯程序演⽰了 sleep() 函数的⽤法:1import threading 2import time 3#定义线程要调⽤的⽅法,*add可接收多个以⾮关键字⽅式传⼊的参数 4def action(*add):5for arc in add:6#暂停 0.1 秒后,再执⾏ 7 time.sleep(0.1)8#调⽤ getName...