//兩條線程交替進(jìn)行//創(chuàng)建線程方式一:繼承Theard類,重寫run方法,調(diào)用start開(kāi)啟線程//總結(jié):注意,線程開(kāi)啟不一定立即執(zhí)行,由CPU調(diào)度執(zhí)行packagecom.zeng.demo01;publicclassTestTheard01extendsThread{@Overridepublicvoidrun(){//run方法線程體for(int i =0; i <20; i++){System.out.println("hello --"+i);}}publicstaticvoidmain(String[] args){//main線程,主線程//創(chuàng)建一個(gè)線程對(duì)象TestTheard01 testTheard01 =newTestTheard01();//調(diào)用start方法開(kāi)啟線程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;//創(chuàng)建線程方法2:實(shí)現(xiàn)runnable接口,重寫run方法,執(zhí)行線程需要丟入runnable接口實(shí)現(xiàn)類,調(diào)用start方法publicclassTestThread02implementsRunnable{@Overridepublicvoidrun(){//run方法線程體for(int i =0; i <200; i++){System.out.println("hello woeld--"+i);}}publicstaticvoidmain(String[] args){//創(chuàng)建runnable接口的實(shí)現(xiàn)類對(duì)象TestThread02 testThread02 =newTestThread02();//創(chuàng)建線程對(duì)象,通過(guò)線程對(duì)象來(lái)開(kāi)啟我們的線程代理// Thread thread = new Thread(testThread02);// thread.start();newThread(testThread02).start();for(int i =0; i <200; i++){System.out.println("hello--"+i);}}}