您好,登錄后才能下訂單哦!
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() # 等待并行的每個線程全都執(zhí)行完畢 在往下走
print("----all threads has finished...", threading.current_thread(), threading.active_count()) # 打印主線程,程序默認有一個主線程
print("cost:", time.time() - start_time) # threading.active_count()活躍線程個數(shù) 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線程執(zhí)行完再往下走 程序進程變成串行了 主程序卡主了
t2.join() # t1執(zhí)行完之后等t2 等待t2 執(zhí)行完之后再往下走
print("main threading....")
# 程序末尾有一個默認的join 守護線程
import threading, time
def run(n):
print("task", n)
time.sleep(2)
print("task done", n, threading.current_thread()) # 打印子線程 如果不設(shè)置為守護線程,那么程序會執(zhí)行到這里
start_time = time.time()
t_objs = []
for i in range(50):
t = threading.Thread(target=run, args=("t %s" % i,))
t.setDaemon(True) # 設(shè)置為守護線程 設(shè)置為守護線程之后,主線程執(zhí)行完之后程序就退出了,不管守護線程有沒有執(zhí)行完都會退出
t.start()
t_objs.append(t) # 把每個線程實例都加進來 不阻塞后面線程的啟動
# for t in t_objs: #取列表里的每個線程
# t.join() #等待并行的每個線程全都執(zhí)行完畢 在往下走
print("----all threads has finished...")
print("cost:", time.time() - start_time)
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。