1叔收、run()/start()的區(qū)別
run()方法只是thread的一個普通方法調用串结,還是在主線程里執(zhí)行瑟押,所有的線程要順序執(zhí)行,一個線程執(zhí)行完畢后才可以繼續(xù)執(zhí)行下面的線程锅很,這樣無法達到寫線程的目的(A線程從3到1執(zhí)行完畢后其馏,B才開始執(zhí)行從3到1凤跑,他們都在一個主線程里爆安,順序執(zhí)行)
start()方法來啟動線程,新線程會執(zhí)行相應的run()方法仔引,真正實現(xiàn)了多線程運行扔仓,這時無需等待run方法體代碼執(zhí)行完畢而可以直接繼續(xù)執(zhí)行下面的代碼,調用start()后咖耘,線程會被放到等待隊列翘簇,等待CPU調度,并不一定馬上開始執(zhí)行儿倒,只是將這個線程置于可動行狀態(tài)版保,然后通過JVM,線程Thread會調用run()方法夫否,執(zhí)行本線程的線程體彻犁。先調用start后調用run(線程C和D是一起執(zhí)行的,從3到1)
package Thread20170329;
class Thread20170329 extends Thread{
private String name;
public Thread20170329(String name) {
this.name = name;
}
public void run() {
int i = 3;
while(i > 0) {
System.out.println(this.name + ":" + (i--));
}
}
public static void main(String[] args) {
Thread20170329 test1 = new Thread20170329("A");
Thread20170329 test2 = new Thread20170329("B");
Thread20170329 test3 = new Thread20170329("C");
Thread20170329 test4 = new Thread20170329("D");
test1.run();
test2.run();
test3.start();
test4.start();
if(Thread.activeCount()>=1)
{
Thread.yield();
}
}
}
執(zhí)行結果如下:
2凰慈、Thread類和Runable接口的區(qū)別
繼承Thread類的線程汞幢,每個線程完成各自的任務(Thread-0和Thread-1分別從5執(zhí)行到1),實現(xiàn)Runnable接口的幾個線程微谓,共同去完成同一個任務(線程A和B線一起執(zhí)行從5到1)
package Runable20170329;
class MyThread implements Runnable{
int i = 5;
public void run() {
while(i > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (i--));
}
}
}
class MyThread1 extends Thread{
int i = 5;
public void run() {
while(i > 0) {
System.out.println(Thread.currentThread().getName() + ":" + (i--));
}
}
}
public class ThreadRunable20170329 {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread r = new MyThread();
Thread t1 = new Thread(r,"A");
Thread t2 = new Thread(r,"B");
t1.start();
t2.start();
MyThread1 mt1 = new MyThread1();
MyThread1 mt2 = new MyThread1();
mt1.start();
mt2.start();
}
}
執(zhí)行結果如下:
用圖表示: