Java的面向?qū)ο缶幊?/a>">Java的面向?qū)ο缶幊?/a>
684
2022-05-29
中斷線程
注意:此處的 Thread.sleep 對(duì)應(yīng)的是主線程,而不是在執(zhí)行的線程
public class InterruptThread {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
Thread.sleep(1); // 主線程暫停1毫秒
t.interrupt(); // 中斷t線程
t.join(); // 等待t線程結(jié)束
System.out.println("end");
}
}
class MyThread extends Thread {
public void run() {
int n = 0;
while (! isInterrupted()) {
n ++;
System.out.println(n + " hello!");
}
}
}
如果線程處于等待中,發(fā)起interrupt請(qǐng)求會(huì)如何?
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread t = new MyThread();
t.start();
Thread.sleep(1000);
t.interrupt(); // 中斷t線程
t.join(); // 等待t線程結(jié)束
System.out.println("end");
}
}
class MyThread extends Thread {
public void run() {
Thread hello = new HelloThread();
hello.start(); // 啟動(dòng)hello線程
try {
hello.join(); // 等待hello線程結(jié)束
} catch (InterruptedException e) {
System.out.println("interrupted!");
}
hello.interrupt();
}
}
class HelloThread extends Thread {
public void run() {
int n = 0;
while (!isInterrupted()) {
n++;
System.out.println(n + " hello!");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
}
main線程通過調(diào)用t.interrupt()從而通知t線程中斷,而此時(shí)t線程正位于hello.join()的等待中,此方法會(huì)立刻結(jié)束等待并拋出InterruptedException。由于我們?cè)趖線程中捕獲了InterruptedException,因此,就可以準(zhǔn)備結(jié)束該線程。在t線程結(jié)束前,對(duì)hello線程也進(jìn)行了interrupt()調(diào)用通知其中斷。如果去掉這一行代碼,可以發(fā)現(xiàn)hello線程仍然會(huì)繼續(xù)運(yùn)行,且JVM不會(huì)退出。
設(shè)置標(biāo)志位
public class Main {
public static void main(String[] args) ?throws InterruptedException {
HelloThread t = new HelloThread();
t.start();
Thread.sleep(1);
t.running = false; // 標(biāo)志位置為false
}
}
class HelloThread extends Thread {
public volatile boolean running = true;
public void run() {
int n = 0;
while (running) {
n ++;
System.out.println(n + " hello!");
}
System.out.println("end!");
}
}
注意到HelloThread的標(biāo)志位boolean running是一個(gè)線程間共享的變量。線程間共享變量需要使用volatile關(guān)鍵字標(biāo)記,確保每個(gè)線程都能讀取到更新后的變量值。
版權(quán)聲明:本文內(nèi)容由網(wǎng)絡(luò)用戶投稿,版權(quán)歸原作者所有,本站不擁有其著作權(quán),亦不承擔(dān)相應(yīng)法律責(zé)任。如果您發(fā)現(xiàn)本站中有涉嫌抄襲或描述失實(shí)的內(nèi)容,請(qǐng)聯(lián)系我們jiasou666@gmail.com 處理,核實(shí)后本網(wǎng)站將在24小時(shí)內(nèi)刪除侵權(quán)內(nèi)容。