今天打算把程序修改成为多线程的,在测试中发现了几个地方,来反映下,先看代码吧:
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,程序是都会等到子线程全部结束才回结束的,而不是在主线程结束后,不管子线程是否结束都结束的。