赞
踩
import threading
class MyThread(threading.Thread):
def __init__(self, thread_name):
super(MyThread, self).__init__(name = thread_name)
# 重写run()方法
def run(self):
print("%s正在运行中......" % self.name)
for i in range(10):
MyThread("thread-" + str(i)).start() # 启动线程
import threading
import time
def show(arg):
time.sleep(1)
print("thread " + str(arg) + " running......")
for i in range(10):
t = threading.Thread(target=show, args=(i,)) # 注意传入的参数一定是一个元组!
t.start()
threading.Thread(self, group=None, target=None, name=None,agrs=(),kwargs=None, *, daemon=None)
import time
import threading
def doWaiting():
print("开始等待:", time.strftime('%H:%M:%S'))
time.sleep(3)
print("结束等待:", time.strftime("%H:%M:%S"))
t = threading.Thread(target=doWaiting)
t.start()
time.sleep(1) # 确保线程已经启动
print("开始工作")
print("结束工作")
import threading import time def doWaiting(): print("开始等待: ", time.strftime("%H:%M:%S")) time.sleep(3) print("结束等待:", time.strftime("%H:%M:%S")) t = threading.Thread(target=doWaiting) t.start() # 确保线程t已经启动 time.sleep(1) print("开始阻塞主线程,等待子线程执行") t.join() # 主线程不要着急走,等等子线程吧!!! 将一直堵塞,直到t运行结束 print("子线程执行完,结束阻塞,主线程继续执行!")
import threading import time def run(): print(threading.current_thread().getName(), "开始工作") time.sleep(2) # 子线程停两秒 print("子线程工作执行完成!") for i in range(3): t = threading.Thread(target=run) t.setDaemon(True) # 把子线程设置为守护进程,必须在start()之前设置!!! t.start() time.sleep(1) # 主线程停1s print("主线程结束运行...") print(threading.active_count()) # 输出活跃的线程数量
import threading class MyThreading(threading.Thread): def __init__(self, func, arg): super(MyThreading, self).__init__() self.func = func self.arg = arg # 重写run()方法 def run(self): self.func(self.arg) def my_func(args): ''' 此处可以把你想让线程做的事定义在这里 ''' print("我是业务函数...") pass obj = MyThreading(my_func, 123) obj.start()
import threading import time number = 0 def plus(): global number # global声明此处的number是外面的全局变量number for _ in range(1000000): # 进行一个大数级别的循环加一运算 number += 1 print("子线程%s运算结束后,number = %s" % (threading.current_thread().getName(), number)) for i in range(2): # 用2个子线程,就可以观察到脏数据 t = threading.Thread(target=plus) t.start() time.sleep(3) # 等待3秒,确保2个子线程都已经结束运算 print("主线程执行完成后,number = ", number)
import threading import time number = 0 def plus(): global number # global声明此处的number是外面的全局变量number for _ in range(1000000): # 进行一个大数级别的循环加一运算 number += 1 print("子线程%s运算结束后,number = %s" % (threading.current_thread().getName(), number)) for i in range(2): # 用2个子线程,就可以观察到脏数据 t = threading.Thread(target=plus) t.start() t.join() # 添加这一行就让两个子线程变成了顺序执行!!!!! time.sleep(3) # 等待3秒,确保2个子线程都已经结束运算 print("主线程执行完成后,number = ", number)
import threading import time number = 0 lock = threading.Lock() # 锁对象! def plus(lk): global number # global声明此处的number是外面的全局变量number lk.acquire() # 开始加锁!!! for _ in range(1000000): # 进行一个大数级别的循环加一运算 number += 1 print("子线程%s运算结束后,number = %s" % (threading.current_thread().getName(), number)) lk.release() # 释放锁,让别的线程也可以访问number!!! for i in range(2): # 用2个子线程,就可以观察到脏数据 t = threading.Thread(target=plus, args=(lock,)) t.start() time.sleep(3) # 等待3秒,确保2个子线程都已经结束运算 print("主线程执行完成后,number = ", number)
import time
import threading
def run(n, se):
se.acquire()
print("run the thread: %s" % n)
time.sleep(1)
se.release()
# 设置5个线程允许同时运行
semaphore = threading.BoundedSemaphore(5)
for i in range(20):
t = threading.Thread(target=run, args=(i, semaphore))
t.start()
import threading import time event = threading.Event() def lighter(): green_time = 5 # 绿灯时间 red_time = 5 # 红灯时间 event.set() # 初始设为绿灯 while True: print("绿灯亮...") time.sleep(green_time) event.clear() print("红灯亮...") time.sleep(red_time) event.set() def run(name): while True: if event.is_set(): # 判断当前是否"放行"状态 print("一辆[%s] 呼啸开过..." % name) time.sleep(1) else: print("一辆[%s]开来,看到红灯,无奈的停下了..." % name) event.wait() print("[%s] 看到绿灯亮了,瞬间飞起....." % name) lighter = threading.Thread(target=lighter,) lighter.start() for name in ['奔驰', '宝马', '奥迪']: car = threading.Thread(target=run, args=(name,)) car.start()
import threading import time num = 0 con = threading.Condition() class Foo(threading.Thread): def __init__(self, name, action): super(Foo, self).__init__() self.name = name self.action = action def run(self): global num con.acquire() print("%s开始执行..." % self.name) while True: if self.action == "add": num += 1 elif self.action == 'reduce': num -= 1 else: exit(1) print("num当前为:", num) time.sleep(1) if num == 5 or num == 0: print("暂停执行%s!" % self.name) con.notify() con.wait() print("%s开始执行..." % self.name) con.release() if __name__ == '__main__': a = Foo("线程A", 'add') b = Foo("线程B", 'reduce') a.start() b.start()
from threading import Timer
def hello():
print("hello world")
# 表示1s后执行hello函数
t = Timer(1, hello)
t.start()
with some_lock:
# 执行任务....
ome_lock.acquire()
try:
# 执行任务..
finally:
some_lock.release()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。