導航:首頁 > 編程語言 > 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停止運行線程相關的資料

熱點內容
計算機編程天才 瀏覽:930
伺服器如何調高解析度 瀏覽:33
機匯app為什麼這么便宜 瀏覽:144
反饋控制演算法 瀏覽:582
命令行沒有了怎麼回事 瀏覽:949
為什麼安卓軟體更新那麼快 瀏覽:838
學編程需要什麼數學基礎 瀏覽:229
沉浸式助眠asmr解壓 瀏覽:125
無證程序員是啥意思 瀏覽:231
成績中等的學生編程專業 瀏覽:132
基於滑動窗口計演算法 瀏覽:210
國家python發展 瀏覽:297
忘記加密密碼後該如何解開 瀏覽:712
python開發文件伺服器 瀏覽:349
重啟svn命令 瀏覽:598
python組合數據類型題庫解析 瀏覽:77
電腦解壓文件的安裝包 瀏覽:468
不培訓能幹程序員嗎 瀏覽:282
編譯器怎麼分享微信 瀏覽:798
四川加密防塵網廠 瀏覽:285