run只是Thread里面的一個普通方法,start是啟動線程的方法。
start()方法讓一個線程進入就緒隊列等待分配 cpu, 分到 cpu 后才調用實現的run()方法。
start()方法不能重復調用, 如果重復調用會拋出異常。
而 run 方法是業務邏輯實現的地方, 本質上和任意一個類的任意一個成員方
法並沒有任何區別, 可以重復執行, 也可以被單獨調用。
1.start()方法來啟動線程,無需等待run方法體代碼執行完畢,可以直接繼續執行下面的代碼;
jvm通過調用Thread類的start()方法來啟動一個線程, 這時此線程是處於就緒狀態, 並沒有運行。
然后通過此Thread類調用方法run()來完成其運行操作的, 這里方法run()稱為線程體,它包含了要執行的這個線程的內容, run方法運行結束, 此線程終止。
然后其他線程再搶cpu的控制權接着執行,這是真正實現了多線程。
2.run()方法當作普通方法的方式調用。程序還是要順序執行,要等待run方法體執行完畢后,才可繼續執行下面的代碼; 程序中只有主線程——這一個線程,其程序執行路徑還是只有一條。這並非多線程,還只是單線程。
public class MyThread1 extends Thread { @Override public void run() { try { System.out.println("run threadName="+ this.currentThread().getName()+"begin"); Thread.sleep(2000); System.out.println("run threadName="+this.currentThread().getName()+"end"); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class Run1 { public static void main(String[] args) { final MyThread1 myThread1 = new MyThread1(); System.out.println("begin="+System.currentTimeMillis()); myThread1.run(); System.out.println("end="+System.currentTimeMillis()); } }
public class Run2 { public static void main(String[] args) { final MyThread1 myThread2 = new MyThread1(); System.out.println("begin="+System.currentTimeMillis()); myThread2.start(); System.out.println("end="+System.currentTimeMillis()); } }