import threading, time
def run(n):
print("task", n)
time.sleep(2)
t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))
t1.start()
t2.start()
run("t1")
run("t2")
import threading, time
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print("running task", self.n)
time.sleep(2)
t1 = MyThread("t1")
t2 = MyThread("t2")
t1.run()
t2.run()
t1.start()
t2.start()
import threading, time
def run(n):
print("task", n)
time.sleep(2)
print("task done", n, threading.current_thread()) # 打印子线程
start_time = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run, args=("t %s" % i,))
t.start()
t_objs.append(t) # 把每个线程实例都加进来 不阻塞后面线程的启动
for t in t_objs: # 取列表里的每个线程
t.join() # 等待并行的每个线程全都执行完毕 在往下走
print("----all threads has finished...", threading.current_thread(), threading.active_count()) # 打印主线程,程序默认有一个主线程
print("cost:", time.time() - start_time) # threading.active_count()活跃线程个数 import time,threading
import time,threading
class MyThread(threading.Thread):
def __init__(self, n, sleep_time):
super(MyThread, self).__init__()
self.n = n
self.sleep_time = sleep_time
def run(self):
print("running task", self.n)
time.sleep(self.sleep_time)
print("task done", self.n)
t1 = MyThread("t1", 2) # 等待2秒
t2 = MyThread("t2", 4) # 等待4秒
t1.start()
t2.start()
t1.join() # wait() 等待t1线程执行完再往下走 程序进程变成串行了 主程序卡主了
t2.join() # t1执行完之后等t2 等待t2 执行完之后再往下走
print("main threading....")
# 程序末尾有一个默认的join 守护线程
import threading, time
def run(n):
print("task", n)
time.sleep(2)
print("task done", n, threading.current_thread()) # 打印子线程 如果不设置为守护线程,那么程序会执行到这里
start_time = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run, args=("t %s" % i,))
t.setDaemon(True) # 设置为守护线程 设置为守护线程之后,主线程执行完之后程序就退出了,不管守护线程有没有执行完都会退出
t.start()
t_objs.append(t) # 把每个线程实例都加进来 不阻塞后面线程的启动
# for t in t_objs: #取列表里的每个线程
# t.join() #等待并行的每个线程全都执行完毕 在往下走
print("----all threads has finished...")
print("cost:", time.time() - start_time)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。