1. 程式人生 > >java多執行緒開發 如何正確關閉執行緒

java多執行緒開發 如何正確關閉執行緒

在java高階開發中,經常會碰到多執行緒,關於執行緒的關閉,可能會用stop() 方法,但是stop是執行緒不安全的,一般採用interrupt,判斷執行緒是否中止採用isInterrupted, 
如果執行緒中有Thread.sleep方法,當設定中斷後,執行這個方法會丟擲異常,就務必在異常中繼續關閉執行緒

Thread thread = null;
thread = new Thread(new Runnable() {
    @Override
    public void run() {
        /*
         * 在這裡為一個迴圈,條件是判斷執行緒的中斷標誌位是否中斷
         */
while (true&&(!Thread.currentThread().isInterrupted())) { try { Log.i("tag","執行緒執行中"+Thread.currentThread().getId()); // 每執行一次暫停40毫秒 //當sleep方法丟擲InterruptedException 中斷狀態也會被清掉 Thread.sleep(40); } catch (InterruptedException e) { e.
printStackTrace(); //如果丟擲異常則再次設定中斷請求 Thread.currentThread().interrupt(); } } } }); thread.start(); //觸發條件設定中斷 thread.interrupt();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

在java高階開發中,經常會碰到多執行緒,關於執行緒的關閉,可能會用stop() 方法,但是stop是執行緒不安全的,一般採用interrupt,判斷執行緒是否中止採用isInterrupted, 
如果執行緒中有Thread.sleep方法,當設定中斷後,執行這個方法會丟擲異常,就務必在異常中繼續關閉執行緒

Thread thread = null;
thread = new Thread(new Runnable() {
    @Override
    public void run() {
        /*
         * 在這裡為一個迴圈,條件是判斷執行緒的中斷標誌位是否中斷
         */
        while (true&&(!Thread.currentThread().isInterrupted())) {
            try {
                Log.i("tag","執行緒執行中"+Thread.currentThread().getId());
                // 每執行一次暫停40毫秒
                //當sleep方法丟擲InterruptedException  中斷狀態也會被清掉
                Thread.sleep(40);
            } catch (InterruptedException e) {
                e.printStackTrace();
                //如果丟擲異常則再次設定中斷請求
                Thread.currentThread().interrupt();
            }
        }
    }
});
thread.start();

//觸發條件設定中斷
thread.interrupt();
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25