python 多執行緒 Threading

2021-08-15 20:34:25 字數 2199 閱讀 1675

簡單的多執行緒:python 2.7

# -*- coding: utf-8 -*-

import threading

defrun_thread

():while

true:

cmd = input("input you choice: ")

print(cmd)

if cmd == 0:

print("thread exit")

break

else:

print("thread running")

t1 = threading.thread(target=run_thread)

t1.setdaemon(true)

t1.start()

print('join')

t1.join()

print('end')

執行結果:

input you choice: join11

thread running

input you choice: 2

2thread running

input you choice: 0

0thread

exit

endprocess finished with exit code 0

t1.join()的作用的是阻塞等待子執行緒t1退出,才返回往下執行

實驗1

將t1.join() 這句注釋掉:

# -*- coding: utf-8 -*-

import threading

defrun_thread

():while

true:

cmd = input("input you choice: ")

print(cmd)

if cmd == 0:

print("thread exit")

break

else:

print("thread running")

t1 = threading.thread(target=run_thread)

t1.setdaemon(true)

t1.start()

print('join')

#t1.join()

print('end')

執行結果:

joininput you choice: 

endprocess finished with

exit code 0

主線程退出的時候,子執行緒也一起退出了

沒有機會輸入資料。

實驗2:

將t1.join() 這句注釋掉:

將t1.setdaemon(true) 這句也注釋掉:

# -*- coding: utf-8 -*-

import threading

defrun_thread

():while

true:

cmd = input("input you choice: ")

print(cmd)

if cmd == 0:

print("thread exit")

break

else:

print("thread running")

t1 = threading.thread(target=run_thread)

#t1.setdaemon(true)

t1.start()

print('join')

#t1.join()

執行結果:

joininput you choice: 

end1

1thread running

input you choice: 2

2thread running

input you choice: 5

5thread running

input you choice: 0

0thread

exit

process finished with exit code 0

主線程退出,子執行緒還在執行,還可以輸入資料

python 多執行緒thread

python通過thread模組支援多執行緒,語法也很簡潔,現在通過乙個例項來看一下python中的多執行緒 import thread import time 保證只額外啟動乙個執行緒 isrunning false 啟動的時間控制,測試時間是23點44分,所以定的是這個時間,可以用於指定定時任務...

Python多執行緒Thread

import threading import time import random def worker name print name 開始執行.n 0 while true print name 輸出 str n n n 1 t random.randint 0,5 print name 休眠...

python多執行緒使用thread

import sched import threading import time defnew task function,delay time,args 定時任務函式 param function 需要執行的函式 param delay time 延遲多少時間執行 param args 需要給f...