如何使主要流程最后结束?
例如,我编写了一些代码,创建了一个 Thread: Test,他创建了另外三个线程 - Test2,但 main 在Test开始之前完成了。
public class Test implements Runnable{
String url;
Thread mThread;
public Test(String url) {
this.url = url;
}
public void start(){
this.mThread = new Thread(this);
this.mThread.start();
}
@Override
public void run() {
System.out.println("TEST STARTED!");
Test2 wclw[] = new Test2[3];
for (int i = 0; i < wclw.length; i++) {
wclw[i] = new Test2(url, i + 1);
wclw[i].start();
}
}
public static void main(String[] args) throws IOException {
System.out.println("MAin STARTED!");
(new Test("qwerty")).start();
System.out.println("MAIN FINISHED");
}
}
class Test2 implements Runnable{
String url;
int threadNum;
Thread mThread;
public Test2(String url, int threadNum) {
this.url = url;
}
public void start(){
this.mThread = new Thread(this);
this.mThread.start();
}
@Override
public void run() {
System.out.println("TEST2 STARTED!");
for (int i = 0; i < 2; i++) {
System.out.println(url);
}
}
}
输出:
MAin STARTED!
MAIN FINISHED
TEST STARTED!
qwerty
TEST2 STARTED!
TEST2 STARTED!
qwerty
qwerty
TEST2 STARTED!
qwerty
qwerty
qwerty