今天打算把程式修改成為多執行緒的,在測試中發現了幾個地方,來反映下,先看程式碼吧:
public TestMain() {
super(“現執行緒1”);
}
public void run() {
for(int i = 0; i < 10; i ) {
System.out.println(Thread.currentThread().getName() “::” i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class TestMain1 extends Thread {
public TestMain1() {
super(“現執行緒2”);
}
public void run() {
for(int i = 0; i < 10; i ) {
System.out.println(Thread.currentThread().getName() “::” i);
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadTest {
public static void main(String[] args) throws Exception {
TestMain t = new TestMain();
TestMain1 t1 = new TestMain1();
t.start();
t1.start();
t.join();
t1.join();
System.out.println(111);
}
}
上個程式碼中,如果沒有join的話,在排程了2個子執行緒後,主執行緒繼續執行,如果有join的話,那麼就等待這個子執行緒執行完了才回接著執行主執行緒的列印”111″。不管有沒有join,程式是都會等到子執行緒全部結束才回結束的,而不是在主執行緒結束後,不管子執行緒是否結束都結束的。
写评论
很抱歉,必須登入網站才能發佈留言。