//兩條線程交替進行//創建線程方式一:繼承Theard類,重寫run方法,調用start開啟線程//總結:注意,線程開啟不一定立即執行,由CPU調度執行packagecom.zeng.demo01;publicclassTestTheard01extendsThread{@Overridepublicvoidrun(){//run方法線程體for(int i =0; i <20; i++){System.out.println("hello --"+i);}}publicstaticvoidmain(String[] args){//main線程,主線程//創建一個線程對象TestTheard01 testTheard01 =newTestTheard01();//調用start方法開啟線程testTheard01.start();for(int i =0; i <20; i++){System.out.println("hello word--"+i);}}}
Thread thread = new Thread(testThread02);
thread.start();
packagecom.zeng.demo01;//創建線程方法2:實現runnable接口,重寫run方法,執行線程需要丟入runnable接口實現類,調用start方法publicclassTestThread02implementsRunnable{@Overridepublicvoidrun(){//run方法線程體for(int i =0; i <200; i++){System.out.println("hello woeld--"+i);}}publicstaticvoidmain(String[] args){//創建runnable接口的實現類對象TestThread02 testThread02 =newTestThread02();//創建線程對象,通過線程對象來開啟我們的線程代理// Thread thread = new Thread(testThread02);// thread.start();newThread(testThread02).start();for(int i =0; i <200; i++){System.out.println("hello--"+i);}}}