Python多執行緒的執行順序及狀態

2021-10-25 15:34:53 字數 1119 閱讀 7363

import threading

import time

class mythread(threading.thread):

def run(self):

for i in range(3):

time.sleep(1)

msg = "i'm " + self.name + '@' + str(i)

print(msg)

def test():

for i in range(5):

my_thread = mythread()

my_thread.start()

if __name__ == '__main__':

test()

返回:

i'm thread-1@0

i'm thread-2@0

i'm thread-3@0

i'm thread-4@0

i'm thread-5@0

i'm thread-2@1

i'm thread-3@1

i'm thread-4@1

i'm thread-1@1

i'm thread-5@1

i'm thread-2@2

i'm thread-3@2

i'm thread-4@2

i'm thread-1@2

i'm thread-5@2

從**和執行結果我們可以看出,多執行緒程式的執行順序是不確定的。當執行到sleep語句時,執行緒將被阻塞(blocked),到sleep結束後,執行緒進入就緒(runnable)狀態,等待排程。而執行緒排程將自行選擇乙個執行緒執行。上面的**中只能保證每個執行緒都執行完整個run函式,但是執行緒的啟動順序、run函式中每次迴圈的執行順序都不能確定。

總結:每個執行緒一定會有乙個名字,儘管上面的例子中沒有指定執行緒物件的name,但是python會自動為執行緒指定乙個名字。

當執行緒的run()方法結束時該執行緒完成。

無法控制線程排程程式,但可以通過別的方式來影響執行緒排程的方式。

執行緒的幾種狀態

java多執行緒執行順序

我們建立兩個執行緒,讓奇數執行緒輸出奇數,偶數執行緒執行輸出偶數。先來看看 實現 package test import org.ietf.jgss.oid public class threadnum extends thread public void run system.out.printl...

多執行緒按照順序執行

自己瀏覽了多個的文章,自己的理解加上的思路,彙總成了這篇文章 1.如何讓多執行緒按照既定順序執行 2.原理 1.直接上 final long start system.currenttimemillis thread t1 new thread catch interruptedexception ...

控制多執行緒執行順序

雖然專案用不上,先備份吧,控制多執行緒執行順序有兩種方法 1.通過join方法保證多執行緒的順序性的特性 join 讓主線程等待子執行緒結束後才能繼續執行 public static void main string args throws interrupterexception 2.excuto...