threading僞多線程

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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章