異步線程的使用


同步與異步的好處壞處

1).同步方法卡界面,因為UI線程忙於計算;異步多線程方法不卡界面,主線程閑置,計算任務交個子線程去做;

2).同步方法慢,只有一個線程計算;異步多線程方法快,多線程並發計算(多線程的資源消耗更多,線程並不是越多越好);

3).異步多線程是無序的:啟動無序,執行時間不確定,結束無序,所以我們不要試圖通過啟動順序或是時間等待來控制流程。

public class SendMailTaskThread {
    //異步線程的調用 public static void startThread(String subject, String from, String[] to, String text, String filename,String mimeType,String pwd, Date date) {
        System.out.println("ES start,thread id="+Thread.currentThread().getId());
        Runnable createRM = new MyTask(參數);
        new Thread(createRM).start();
        System.out.println("ES shutdown, thread id="+Thread.currentThread().getId());
        
    }

}

class MyTask implements Runnable{
    private String subject;
    
    public MyTask(參數) {
        super();
        this.subject = subject;
    }

    @Override
    public void run() {
        System.out.println("creating MyTask, thread id="+Thread.currentThread().getId());
        try {
            try {
                【具體業務實現】  ----這里寫自己的業務  
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("end MyTask, thread id="+Thread.currentThread().getId());
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM