java中断一个线程
生活随笔
收集整理的這篇文章主要介紹了
java中断一个线程
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
調用Thread的中斷方法interrupt()來中斷一個線程
public class ThreadDemo {public static void main(String[] args) {Runnable myRunnable = new MyThread(); // 創建一個Runnable實現類的對象Thread thread = new Thread(myRunnable,"線程A");// 調用start()方法使得線程進入就緒狀態thread.start();if(!thread.isInterrupted()){//如果線程沒有被中斷System.out.println("準備中斷線程");thread.interrupt();}} }class MyThread implements Runnable {@Overridepublic void run() {System.out.println(Thread.currentThread().getName());try {Thread.sleep(10000);} catch (InterruptedException e) {System.out.println("線程被中斷");}} }執行結果
總結
以上是生活随笔為你收集整理的java中断一个线程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java获取当前线程的名字以及为线程命名
- 下一篇: java设置优先级