1. 程式人生 > 其它 >使用“return”語句停止執行緒的缺點與解決方案——T1118

使用“return”語句停止執行緒的缺點與解決方案——T1118

技術標籤:多執行緒java多執行緒

package 多執行緒技能1;

/**
 * 使用“return”語句停止執行緒的缺點與解決方案
 */

/**
 * 測試
 */
class MyThreadT1118 extends Thread{
    @Override
    public void run() {
        while(true){
            if(this.isInterrupted()){
                System.out.println("停止了!");
                return;
            }
System.out.println("timer="+ System.currentTimeMillis()); } } } /** * 測試類2 */ class MyThread1T1118 extends Thread{ @Override public void run() { //insert操作 if(interrupted()){ System.out.println("寫入long info"); return
; } //update操作 if(interrupted()){ System.out.println("寫入log info"); return; } //delete 操作 if(interrupted()){ System.out.println("寫入log info"); return; } //select操作 if
(interrupted()){ System.out.println("寫入log info"); return; } System.out.println("for for for for for "); } } /** * 測試類 */ class MyThread2T1118 extends Thread{ @Override public void run() { try { //insert 操作 if(interrupted()){ throw new InterruptedException(); } //update操作 if(interrupted()){ throw new InterruptedException(); } //delete操作 if(interrupted()){ throw new InterruptedException(); } //select操作 if(interrupted()){ throw new InterruptedException(); } System.out.println("for for for for for "); } catch (InterruptedException e) { System.out.println("寫入log info"); e.printStackTrace(); } } } /** * 執行類 */ class RunT1118{ public RunT1118() throws InterruptedException { MyThreadT1118 myThreadT1118=new MyThreadT1118(); myThreadT1118.start(); Thread.sleep(2000); myThreadT1118.interrupt(); } } /** * 執行類2 */ class Run2T1118{ public Run2T1118() throws InterruptedException { MyThread1T1118 myThread1T1118=new MyThread1T1118(); MyThread2T1118 myThread2T1118=new MyThread2T1118(); myThread1T1118.start(); Thread.sleep(1000); myThread1T1118.interrupt(); myThread2T1118.start(); Thread.sleep(1000); myThread2T1118.interrupt(); } } public class T1118 { public static void main(String[] args) throws InterruptedException { /** * 雖然使用“return"比”拋異常“法在程式碼結構上可以更加方便實現執行緒的停止,不過 * 還是建議使用“拋異常”法,因為在catch塊中可以對拋異常的資訊進行統一處理 */ //RunT1118 runT1118=new RunT1118(); System.out.println("---------------------"); Run2T1118 run2T1118=new Run2T1118(); } }