java的线程中断
在java中中斷線程可以使用interrupt()函數。此函數雖然不能終止線程的運行,但是可以改變線程的狀態為true
即:isInterrupted()的值返回為true
注意:當函數調用了已經被阻塞的線程后,被阻塞的線程將會接收到一個InterruptedException異常。即當前線程即可終止。
例如:
package TestThread.ThreadSynchronized;public class TestWaitAll {public static void main(String[] args) {// 創建線程對象Test1 test1 = new Test1();// 創建線程Thread t = new Thread(test1, "線程1");Thread t1 = new Thread(test1, "線程2");Thread t2 = new Thread(test1, "線程3");Thread t3 = new Thread(test1, "線程4");// 這是喚醒線程Test2 test2 = new Test2(test1, "喚醒線程");t.start();t1.start();t2.start();t2.interrupt();// 中斷線程t3.start();try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}// 啟動喚醒線程test2.start();}
}class Test1 implements Runnable {public void run() {synchronized (this) {// 當被阻塞的線程調用了interrupt后將會發生異常try {this.wait();System.out.println(Thread.currentThread().getName() + ":我沒有被中斷,我可以執行到!");} catch (InterruptedException e) {System.out.println(Thread.currentThread().getName() + ":被中斷了!");}}}
}/*** @author CHAI015 生成喚醒類*/
class Test2 extends Thread {/*** Test1 為喚醒對象 name 為線程名稱*/private Test1 test1;String name;/*** @param test1喚醒對象* @param name喚醒名稱*/public Test2(Test1 test1, String name) {super(name);this.name = name;this.test1 = test1;}public void run() {synchronized (test1) {test1.notifyAll();// 針對當前對象執行喚醒所有線程的操作System.out.println(Thread.currentThread().getName() + ":喚醒線程執行成功!");}}
}
運行結果為:
?
轉載于:https://www.cnblogs.com/chaiyesong/p/6610715.html
總結
- 上一篇: 有没有哪位大佬有漫威电影所有的资源
- 下一篇: L3-010. 是否完全二叉搜索树