終止執行緒的執行
目錄- 終止執行緒的執行
- 一、強制終止執行緒的執行
- 二、合理終止執行緒的執行
一、強制終止執行緒的執行
強制終止用的是stop()方法,因為這種方法會丟失資料,所以一般不采用這種方法,
原理是直接殺死執行緒,這樣的話執行緒中沒有保存的資料就會丟失
/*
在java中強制終止一個執行緒
*/
public class ThreaTest09 {
public static void main(String[] args) {
Thread t=new Thread(new Thread09());
t.setName("t");
t.start();
try {
Thread.sleep(1000*5);
} catch (InterruptedException e) {
e.printStackTrace();
}
//stop()強行終止,容易丟失資料,這種方式是直接殺死執行緒,執行緒沒有保存的資料會丟失,不建議使用
t.stop();
}
}
//一秒列印一個數字
class Thread09 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"----> begin"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
輸出:
t----> begin0
t----> begin1
t----> begin2
t----> begin3
t----> begin4
可以看出,我們在主執行緒當中的休眠5s并沒有執行!
二、合理終止執行緒的執行
既然上面那種方法會有容易丟失資料的缺點,那么我們在執行緒的操作中怎么去合理終止執行緒的運行呢?
我們可以定義一個布林值,用來控制執行緒的結束
代碼:
public class ThreadTest10 {
public static void main(String[] args) {
Thread10 thread10 = new Thread10();
Thread t=new Thread(thread10);
t.setName("t");
t.start();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
thread10.run=false;
}
}
class Thread10 implements Runnable{
boolean run=true;
@Override
public void run() {
for (int i = 0; i < 10; i++) {
if (run){
System.out.println(Thread.currentThread().getName()+"----->"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}else {
//終止當前執行緒
//return就是結束,如果還有未保存的可以在這里執行保存,然后再結束
//save....
return;
}
}
}
}
輸出:
t----->0
t----->1
t----->2
t----->3
t----->4
可以看出在程式中正常執行,當主執行緒休眠5s之后就調開始執行,把true改為false停止了程式,執行緒正常結束!
本文來自博客園,作者:星余明,轉載請注明原文鏈接:https://www.cnblogs.com/lingstar/p/16534431.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/500623.html
標籤:Java
上一篇:JetBrains GoLand 2022 (GO語言集成開發工具環境)
下一篇:自定義查詢--關于倒排索引的研究
