python3 基本使用多執行緒

2021-09-07 01:38:00 字數 1107 閱讀 7706

#coding=utf-8

import threading #進口threading

from time import sleep

import time

def task1():

print ("task 1 executed." )

sleep(1)

def task2():

print ("task 2 executed." )

sleep(5)

print("多執行緒:")

starttime=time.time(); #記錄開始時間

threads = #建立乙個執行緒列表,用於存放須要執行的子執行緒

t1 = threading.thread(target=task1) #建立第乙個子執行緒。子執行緒的任務是呼叫task1函式。注意函式名後不能有()

t2 = threading.thread(target=task2)#建立第二個子執行緒

for t in threads: #遍歷執行緒列表

t.setdaemon(true) #將執行緒宣告為守護執行緒。必須在start() 方法呼叫之前設定。假設不設定為守護執行緒程式會被無限掛起

t.start() #啟動子執行緒

endtime=time.time();#記錄程式結束時間

totaltime=endtime-starttime;#計算程式執行耗時

print ("耗時:秒" .format(totaltime)); #格式輸出耗時

print('---------------------------')

#下面為普通的單執行緒執行過程。不需解釋

print("單執行緒:")

starttime=time.time();

task1();

task2();

endtime=time.time();

totaltime=endtime-starttime;

print ("耗時:秒" .format(totaltime));

結果:

python3 多執行緒的使用

示例1 import threading from time import sleep class forthread threading.thread def init self,event threading.thread.init self self.name 我的多執行緒 self.even...

Python3多執行緒

學習python執行緒 python3 執行緒中常用的兩個模組為 thread threading 推薦使用 thread 模組已被廢棄。使用者可以使用 threading 模組代替。所以,在 python3 中不能再使用 thread 模組。為了相容性,python3 將 thread 重新命名為...

python3 多執行緒

多執行緒簡介 執行緒 thread 也稱輕量級程序,時作業系統能夠進行運算排程的最小單位,它被包涵在程序之中,時程序中的實際運作單位。執行緒自身不擁有資源,只擁有一些在執行中必不可少的資源,但他可與同屬乙個程序的其他執行緒共享程序所擁有的全部資源。乙個執行緒可以建立和撤銷另乙個執行緒,同一程序中的多...