1. 程式人生 > >java 關閉一個正在執行的執行緒

java 關閉一個正在執行的執行緒

中斷(Interrupt)一個執行緒意味著在該執行緒完成任務之前停止其正在進行的一切,有效地中止其當前的操作。執行緒是死亡、還是等待新的任務或是繼續執行至下一步,就取決於這個程式。雖然初次看來它可能顯得簡單,但是,你必須進行一些預警以實現期望的結果。你最好還是牢記以下的幾點告誡。

首先,忘掉Thread.stop方法。雖然它確實停止了一個正在執行的執行緒,然而,這種方法是不安全也是不受提倡的,這意味著,在未來的JAVA版本中,它將不復存在。

1:

  1. publicstaticvoid main(String[] args) throws Exception {  
  2.         MyThread mt = 
    new MyThread();  
  3.         Thread t = new Thread(mt);  
  4.         System.out.println("System is ready to start thread");  
  5.         t.start();  
  6.         Thread.sleep(3000);  
  7.         System.out.println("System is ready to stop thread");  
  8. //執行緒沒有處於阻塞狀態,呼叫執行緒對應的interrupt()不能讓執行的執行緒停止下來
  9.         t.interrupt();  
  10.     }  
  11. staticclass MyThread implements Runnable {  
  12. publicvolatileboolean stop = false;  
  13. privatevoid dosomethig() throws InterruptedException {  
  14. long time = System.currentTimeMillis();  
  15. while(System.currentTimeMillis() - time < 1000) {  
  16.             }  
  17.             System.out.println("all things had been done!!"
    );  
  18.         }  
  19. @Override
  20. publicvoid run() {  
  21. try {  
  22. while(!stop) {  
  23.                     System.out.println(Thread.currentThread().getName() + " is running..");  
  24.                     dosomethig();  
  25.                 }  
  26.             } catch (InterruptedException e) {  
  27.                 e.printStackTrace();  
  28.             } finally {  
  29.                 System.out.println(Thread.currentThread().getName() + " is exiting under request.");  
  30.             }  
  31.         }  
  32.     } 
  1. 執行結果:  
  2. System is ready to start thread  
  3. Thread-0 is running..  
  4. all things had been done!!  
  5. Thread-0 is running..  
  6. all things had been done!!  
  7. Thread-0 is running..  
  8. all things had been done!!  
  9. Thread-0 is running..  
  10. System is ready to stop thread  
  11. all things had been done!!  
  12. Thread-0 is running..  
  13. all things had been done!!  
  14. Thread-0 is running..  
  15. all things had been done!!  
  16. Thread-0 is running..  
  17. all things had been done!!  
  18. Thread-0 is running..  

2:

  1. publicstaticvoid main(String[] args) throws Exception {  
  2.         MyThread mt = new MyThread();  
  3.         Thread t = new Thread(mt);  
  4.         System.out.println("System is ready to start thread");  
  5.         t.start();  
  6.         Thread.sleep(3000);  
  7.         System.out.println("System is ready to stop thread");  
  8. //      t.interrupt();
  9. //當執行緒沒有處於阻塞狀態,通過改變標誌量,可以讓執行緒停止執行
  10.         mt.stop = true;  
  11.     } 
  1. 執行結果:  
  2. System is ready to start thread  
  3. Thread-0 is running..  
  4. all things had been done!!  
  5. Thread-0 is running..  
  6. all things had been done!!  
  7. Thread-0 is running..  
  8. System is ready to stop thread  
  9. all things had been done!!  
  10. Thread-0 is exiting under request. 

3:

  1. publicstaticvoid main(String[] args) throws Exception {  
  2.         MyThread mt = new MyThread();  
  3.         Thread t = new Thread(mt);  
  4.         System.out.println("System is ready to start thread");  
  5.         t.start();  
  6.         Thread.sleep(3000);  
  7.         System.out.println("System is ready to stop thread");  
  8. //      t.interrupt();
  9. //此時執行緒一直處於阻塞狀態,無法檢查標誌量,所以僅通過改變標誌量無法停止執行緒
  10.         mt.stop = true;  
  11.     }  
  12. staticclass MyThread implements Runnable {  
  13. publicvolatileboolean stop = false;  
  14. privatevoid dosomethig() throws InterruptedException {  
  15. //          long time = System.currentTimeMillis();
  16. //          while(System.currentTimeMillis() - time < 1000) {
  17. //              
  18. //          }
  19.             Thread.currentThread().join();  
  20.             System.out.println("all things had been done!!");  
  21.         }  
  22. @Override
  23. publicvoid run() {  
  24. try {  
  25. while(!stop) {  
  26.                     System.out.println(Thread.currentThread().getName() + " is running..");  
  27.                     dosomethig();  
  28.                 }  
  29.             } catch (InterruptedException e) {  
  30.                 e.printStackTrace();  
  31.             } finally {  
  32.                 System.out.println(Thread.currentThread().getName() + " is exiting under request.");  
  33.             }  
  34.         }  
  35.     } 
  1. 執行結果:  
  2. System is ready to start thread  
  3. Thread-0 is running..  
  4. System is ready to stop thread  

4:

  1. publicstaticvoid main(String[] args) throws Exception {  
  2.         MyThread mt = new MyThread();  
  3.         Thread t = new Thread(mt);  
  4.         System.out.println("System is ready to start thread");  
  5.         t.start();  
  6.         Thread.sleep(3000);  
  7.         System.out.println("System is ready to stop thread");  
  8. //通過呼叫執行緒物件上的interrupt() 正在執行的執行緒物件會接收到一個InterruptedException異常,從而停止執行
  9.                   t.interrupt();  
  10. //      mt.stop = true;
  11.     } 
  1. 執行結果:  
  2. System is ready to start thread  
  3. Thread-0 is running..  
  4. System is ready to stop thread  
  5. java.lang.InterruptedException  
  6. Thread-0 is exiting under request.  
  7.     at java.lang.Object.wait(Native Method)  
  8.     at java.lang.Thread.join(Thread.java:1143)  
  9.     at java.lang.Thread.join(Thread.java:1196)  
  10.     at com.thread.DeadLockTest$MyThread.dosomethig(DeadLockTest.java:29)  
  11.     at com.thread.DeadLockTest$MyThread.run(DeadLockTest.java:38)  
  12.     at java.lang.Thread.run(Thread.java:619

5:中斷I/O操作

  1. publicstaticvoid main(String[] args) throws Exception {  
  2.         MyThread mt = new MyThread();  
  3.         Thread t = new Thread(mt);  
  4.         System.out.println("System is ready to start thread");  
  5.         t.start();  
  6.         Thread.sleep(3000);  
  7.         System.out.println("System is ready to stop thread");  
  8.         t.interrupt();  
  9.         mt.stop = true;  
  10.         mt.socket.close();  
  11.     }  
  12. staticclass MyThread implements Runnable {  
  13. publicvolatileboolean stop = false;  
  14.         ServerSocket socket = null;  
  15. privatevoid dosomethig() throws InterruptedException, IOException {  
  16. //          long time = System.currentTimeMillis();
  17. //          while(System.currentTimeMillis() - time < 1000) {
  18. //              
  19. //          }
  20. //          Thread.currentThread().join();
  21.             socket = new ServerSocket(9999);  
  22. //這裡需要呼叫Socket對應的close方法 這樣子 被阻塞的執行緒會接收到一個SocketException 從而停止執行
  23.             socket.accept();  
  24.             System.out.println("all things had been done!!");  
  25.         }  
  26. @Override
  27. publicvoid run() {  
  28. try {  
  29. while(!stop) {  
  30.                     System.out.println(Thread.currentThread().getName() + " is running..");  
  31.                     dosomethig();  
  32.                 }  
  33.             } catch (InterruptedException e) {  
  34.                 e.printStackTrace();  
  35.             } catch (IOException e) {  
  36.                 e.printStackTrace();  
  37.             } finally {  
  38.                 System.out.println(Thread.currentThread().getName() + " is exiting under request.");  
  39.             }  
  40.         }  
  41.     } 
  1. 執行結果:  
  2. System is ready to start thread  
  3. Thread-0 is running..  
  4. System is ready to stop thread  
  5. java.net.SocketException: socket closed  
  6. Thread-0 is exiting under request.  
  7.     at java.net.PlainSocketImpl.socketAccept(Native Method)  
  8.     at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:384)  
  9.     at java.net.ServerSocket.implAccept(ServerSocket.java:453)  
  10.     at java.net.ServerSocket.accept(ServerSocket.java:421)  
  11.     at com.thread.DeadLockTest$MyThread.dosomethig(DeadLockTest.java:33)  
  12.     at com.thread.DeadLockTest$MyThread.run(DeadLockTest.java:42)  
  13.     at java.lang.Thread.run(Thread.java:619

    相關推薦

    java 關閉一個正在執行執行

    中斷(Interrupt)一個執行緒意味著在該執行緒完成任務之前停止其正在進行的一切,有效地中止其當前的操作。執行緒是死亡、還是等待新的任務或是繼續執行至下一步,就取決於這個程式。雖然初次看來它可能顯得簡單,但是,你必須進行一些預警以實現期望的結果。你最好還是牢記以下的幾

    Java 輸入一個整數,將其用中文打印出來

    輸入一個正整數,將其用中文打印出來。使用java 實現 import  java.util.Scanner; public static void main(String[]  arge){          

    今天開始學Java 給定一個整數,編寫程式計算有多少對質數的和等於輸入的這個整數,並輸出結果。

    給定一個正整數,編寫程式計算有多少對質數的和等於輸入的這個正整數,並輸出結果。輸入值小於1000。如,輸入為10, 程式應該輸出結果為2。(共有兩對質數的和為10,分別為(5,5),(3,7)) 輸入描述:輸入包括一個整數n,(3 ≤ n < 1000)輸出描述:輸出對

    java 輸入一個整數求各個位數這和

    package javaSE_第二週; import java.util.Scanner; /*  *計算一個正整數求它各個位數之和  *問題:編寫一個程式,讓使用者輸入一個三位數的正整數值,然後計算該數各位數的和,  *例如:如果輸入的數是123,則計算結果是6  *此方

    Java執行的傳說(3)——如何關閉一個正在accept的ServerSocket?

    加入一個ServerSocket正在另一個執行緒堵塞accept,那如何停止accept或者關閉Socket?Server socket 設定下超時 setSoTimeout 然後在Listen執行緒中用interrupt其實直接close socket也可以,不過會丟擲異

    Java建立一個執行的三種方式

    步驟一:執行緒概念 首先要理解程序(Processor)和執行緒(Thread)的區別 程序:啟動一個LOL.exe就叫一個程序。 接著又啟動一個DOTA.exe,這叫兩個程序。 執行緒:執行緒是在程序內部同時做的事情,比如在LOL裡,有很多事情要同時做,比如"蓋倫” 擊殺“

    JAVA定義一個執行池,迴圈遍歷list

    文章目錄 前言 思路 下面是我自己專案中的呼叫程式碼,供你參考(ProcessNumTask就是那個實現Callable的任務): Callable與Future的介紹 Callable的介面定義如下:

    JAVA 建立一個執行的三種方式

    建立多執行緒-實現Runnable介面 建立類Battle,實現Runnable介面 啟動的時候,首先建立一個Battle物件,然後再根據該battle物件建立一個執行緒物件,並啟動   Battle battle1 = new Battle(gareen,teemo); new Thread(battle1

    java建立一個執行的兩種方法及區別

    第一種方法:繼承Thread類 public class NewThread extends Thread { public void run() { for(int i=0;i<20;i++) { System.out.println(i); } } }

    dubbo如何關閉一個執行池的?

      public static void gracefulShutdown(Executor executor, int timeout) { if (!(executor instanceof ExecutorService) || isShutdown(executor)

    Java終止一個已啟動的執行

    import java.math.BigInteger; import java.security.MessageDigest; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import

    Java每天一個知識點+Demo-多執行相關命令

    一 多執行緒相關命令介紹 1 wait()  sleep()  (1)這兩個方法來自不同的類分別是wait()來自Thread,sleep()來自Object。  (2) 最主要是sleep方法沒有釋放鎖,sleep使當前執行緒進入停滯狀態(阻塞當前執行緒),讓出cpu

    Java停止一個執行的幾種方法

    Java中停止一個執行緒有三種方法,分別是stop,interrupt和設定標誌位,我們依次來看一下這三種方法。 首先不推薦使用stop方法,原因有兩點: 1、原則上只要一呼叫thread.stop()方法,執行緒就會立即停止,並丟擲ThreadDeath error,查看

    Java例項說明 100個執行同時向一個銀行賬戶中存入1元錢,在沒有使用同步機制和使用同步機制情況下的執行情況

    銀行賬戶類: public class Account {private double balance; // 賬戶餘額public void deposit(double money) {double newBalance = balance + money;try {T

    java-建立一個執行,在控制檯不斷輸出當前時間,精確到時分秒,每隔一秒輸出一次。

    對其實現的一個方法是:          採用繼承Thread類 重寫run方法。 import java.text.SimpleDateFormat; import java.util.Date; /** * 建立一個執行緒,在控制檯不斷輸出當前時間,精確到時分秒,

    如何關閉一個swingworker執行

    如果你在一個 SwingWorker 裡只用到了 doInBackground 方法 那和一個普通的 Thread 是沒有區別的 當你需要更新介面的時候,應該呼叫 publish 方法,通知 process 方法處理相關的介面更新 API 裡寫的很清楚 SwingWorker 的生命週期中包含三個執行緒:

    php 中preg_replace執行一個則表達式的搜索和替換

    cnblogs param subject bject placement family sub ica ans preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $lim

    Java 知識 - 集合、多執行、IO、JVM

    GitHub 專案地址 Collection Java Collection 新增、刪除等操作時可選操作,如 Arrays.asList,會產生固定大小的集合,會丟擲 UnsupportedOperationException Set HashSet、TreeSet、LinkedH

    java併發程式設計實戰】—–執行基本概念

    轉自 http://cmsblogs.com/?p=1638 共享和可變 要編寫執行緒安全的程式碼,其核心在於對共享的和可變的狀態進行訪問。 “共享”就意味著變數可以被多個執行緒同時訪問。我們知道系統中的資源是有限的,不同的執行緒對資源都是具有著同等的使用權。有限、公平就意味著競爭

    java併發程式設計一一多執行之間通訊(一)

    1.多執行緒之間如何實現通訊 多執行緒之間通訊,其實就是多個執行緒在操作同一個資源,但是操作的動作不同。 1.1什麼是多執行緒之間通訊? 需求:第一個執行緒寫入(input)使用者,另一個執行緒讀取(out)使用者。實現讀一個,寫一個操作。 1.2多執行緒之間通訊需求?