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

熱點內容
什麼是適合自己的app 瀏覽:451
雲伺服器怎麼補漏洞 瀏覽:176
如何看自己的安卓是什麼等級 瀏覽:633
被丁磊挖走的程序員 瀏覽:19
gsk980ta編程 瀏覽:507
單片機離線 瀏覽:84
解壓助眠敲擊外國長指甲 瀏覽:421
3次元編程 瀏覽:803
夫妻傳送英文命令 瀏覽:316
程序員題代做 瀏覽:950
戴爾伺服器怎麼擴大內存 瀏覽:641
解壓包密碼消失 瀏覽:135
昆侖通態觸摸屏用戶窗加密 瀏覽:564
農信app怎麼看日額 瀏覽:865
iphone備忘錄包含視頻無法加密 瀏覽:283
抖音快手紅包源碼 瀏覽:137
程序員資源分析 瀏覽:586
linux交換分區大小 瀏覽:922
mt怎麼編譯 瀏覽:337
qq郵箱打開pdf 瀏覽:461