線程中斷 thread.interrupt()的用法

  1. 
    
    public class Main extends Thread{
       boolean stop = false;
       public static void main(String[] args) throws Exception {
          Thread thread = new Thread(new Main(),"My Thread2");
          System.out.println( "Starting thread..." );
          thread.start();
          Thread.sleep( 3000 );
          System.out.println( "Interrupting thread..." );
          thread.interrupt();
          System.out.println("線程是否中斷:" + thread.isInterrupted());
          Thread.sleep( 3000 );
          System.out.println("Stopping application..." );
       }
       public void run() {
          while(!stop){
             System.out.println( "My Thread is running..." );
             // 讓該循環持續一段時間,使上面的話打印次數少點
             long time = System.currentTimeMillis();
             while((System.currentTimeMillis()-time < 1000)) {
             }
             if(Thread.currentThread().isInterrupted()) {
                return;
             }
          }
          System.out.println("My Thread exiting under request..." );
       }
    }
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章