日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

java的线程中断

發布時間:2023/11/27 生活经验 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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

總結

以上是生活随笔為你收集整理的java的线程中断的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。