導航:首頁 > 編程語言 > java停止運行線程

java停止運行線程

發布時間:2023-08-16 06:33:06

『壹』 java 中如何使線程運行一定時間後停止

java中使線程運行一定時間後停止,可以設置一個變數,當滿足條件則退出線程:

importstaticjava.lang.Thread.currentThread;
importjava.util.concurrent.TimeUnit;
publicclassThreadPauseDemo{
publicstaticvoidmain(Stringargs[])throwsInterruptedException{
Gamegame=newGame();
Threadt1=newThread(game,"T1");
t1.start();
//現在停止Game線程
System.out.println(currentThread().getName()+"isstoppinggamethread");
game.stop();
//查看Game線程停止的狀態
TimeUnit.MILLISECONDS.sleep(200);
System.out.println(currentThread().getName()+"isfinishednow");
}
}

classGameimplementsRunnable{
=false;
publicvoidrun(){
while(!isStopped){
System.out.println("Gamethreadisrunning......");
System.out.println("Gamethreadisnowgoingtopause");
try{
Thread.sleep(200);
}catch(InterruptedExceptione){
e.printStackTrace();
}
System.out.println("Gamethreadisnowresumed......");
}
System.out.println("Gamethreadisstopped......");
}
publicvoidstop(){
isStopped=true;
}
}

程序輸出如下:

Game thread is running......
main is stopping game thread
Game thread is now going to pause
Game thread is now resumed......
Game thread is stopped......
main is finished now

『貳』 Java中如何正確而優雅的終止運行中的線程

Java中終止線程的方式主要有三種:

1、使用stop()方法,已被棄用。原因是:stop()是立即終止,會導致一些數據被到處理一部分就會被終止,而用戶並不知道哪些數據被處理,哪些沒有被處理,產生了不完整的「殘疾」數據,不符合完整性,所以被廢棄。So, forget it!

2、使用volatile標志位

看一個簡單的例子:

首先,實現一個Runnable介面,在其中定義volatile標志位,在run()方法中使用標志位控製程序運行

{

//定義退出標志,true會一直執行,false會退出循環
//使用volatile目的是保證可見性,一處修改了標志,處處都要去主存讀取新的值,而不是使用緩存
publicvolatilebooleanflag=true;

publicvoidrun(){
System.out.println("第"+Thread.currentThread().getName()+"個線程創建");

try{
Thread.sleep(1000L);
}catch(InterruptedExceptione){
e.printStackTrace();
}

//退出標志生效位置
while(flag){
}
System.out.println("第"+Thread.currentThread().getName()+"個線程終止");
}
}

然後,在main()方法中創建線程,在合適的時候,修改標志位,終止運行中的線程。

publicclassTreadTest{
publicstaticvoidmain(String[]arg)throwsInterruptedException{
MyRunnablerunnable=newMyRunnable();

//創建3個線程
for(inti=1;i<=3;i++){
Threadthread=newThread(runnable,i+"");
thread.start();
}
//線程休眠
Thread.sleep(2000L);
System.out.println("——————————————————————————");
//修改退出標志,使線程終止
runnable.flag=false;
}
}

最後,運行結果,如下:

第1個線程創建
第2個線程創建
第3個線程創建
--------------------------
第2個線程終止
第1個線程終止
第3個線程終止

3、使用interrupt()中斷的方式,注意使用interrupt()方法中斷正在運行中的線程只會修改中斷狀態位,可以通過isInterrupted()判斷。如果使用interrupt()方法中斷阻塞中的線程,那麼就會拋出InterruptedException異常,可以通過catch捕獲異常,然後進行處理後終止線程。有些情況,我們不能判斷線程的狀態,所以使用interrupt()方法時一定要慎重考慮。

『叄』 java線程如何停止

通過調用interrupt方法可以使得處於阻塞狀態的線程拋出一個異常,即interrupt方法可以用來中斷一個正處於阻塞狀態的線程;另外,改方法還會設置線程的中斷狀態(註:isInterrupted()可以用來查詢中斷狀態)。

閱讀全文

與java停止運行線程相關的資料

熱點內容
程序員和施工員哪個有前途 瀏覽:614
浙江百兆伺服器雲空間 瀏覽:827
php和html5學哪個比較好 瀏覽:388
瑜伽pdf下載地址 瀏覽:252
小花貓app改名叫什麼 瀏覽:837
編程器固件修改 瀏覽:523
沈陽技校有程序員嗎 瀏覽:300
各行app的基金有什麼不一樣嗎 瀏覽:62
python編譯器怎麼裝 瀏覽:73
新浪php筆試題 瀏覽:138
新時達伺服器如何自學習 瀏覽:27
程序中什麼命令用來輸入單字元 瀏覽:59
php是否有數據 瀏覽:141
虛擬雲伺服器是什麼意思 瀏覽:279
vb是編譯性語言嗎 瀏覽:209
json格式用什麼編譯器 瀏覽:319
word轉pdf代碼 瀏覽:802
單片機中如何編程 瀏覽:739
cad常見的快捷命令 瀏覽:625
伺服器端有什麼 瀏覽:325