同步與異步的好處壞處
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()); } }