java的線程中斷,java線程中斷

來源:互聯網
上載者:User

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() + ":喚醒線程執行成功!");}}}

運行結果為:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.