java的線程中斷,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() + ":喚醒線程執行成功!");}}}
運行結果為: