執行緒併發庫(建立執行緒 守護執行緒 暫停執行緒)

2021-08-26 13:20:47 字數 951 閱讀 6308

開啟執行緒第一種方式:

public class test 

}class mythread extends thread

}

開啟執行緒第二種方式:

public class test 

}class myrunnable implements runnable

}

使用匿名內部類建立子執行緒:

new thread("執行緒3") 

}.start();

new thread(new runnable()

}, "執行緒4").start();

守護執行緒:

final thread t1 = new thread()  catch (interruptedexception e) }}

};thread t2 = new thread() catch (interruptedexception e) }}

};t2.setdaemon(true); // 設定為守護執行緒, 不單獨執行

t1.start(); // 5次, 5秒就結束了

t2.start(); // 10次, 需要10秒

// 程式在所有非守護執行緒執行結束之後才結束

當前執行緒暫停,等待加入的執行緒執行結束之後再繼續:

final thread t1 = new thread()  catch (interruptedexception e) }}

};thread t2 = new thread() catch (interruptedexception e) }}

};t1.start(); // 5次, 5秒就結束了

t2.start(); // 10次, 需要10秒

併發程式設計 守護執行緒

守護執行緒的意思 主程序結束後,不在執行未結束的執行緒了 from threading import thread from time import sleep class mythread thread def init self,name thread.init self self.name n...

執行緒 守護執行緒

一類是 使用者執行緒 一類是 守護執行緒 後台執行緒 一般的守護執行緒是乙個死迴圈,所有的使用者執行緒結束後,守護執行緒自動結束 將乙個死迴圈執行緒設定為守護執行緒就可以了,用setdaemon 方法。舉個例子 先是未設定為守護執行緒的執行緒 public class main1 catch int...

主線程 守護執行緒 非守護執行緒

main,但不是守護執行緒。是指在程式執行的時候在後台提供一種通用服務的執行緒。如gc。也叫使用者執行緒,由使用者建立。主線程和守護執行緒一起銷毀 主線程和非守護執行緒互不影響。例如 package com.peng.thread 1 使用者執行緒 非守護執行緒 有主線程建立 2 守護執行緒和主線程...