MyThread.java
/**
* 线程类,模拟处理业务逻辑
*
*/
public class MyThread extends Thread {
private int num = 3;
private String thrdName;
public MyThread(String thrdName) {
this.thrdName = thrdName;
this.setName(thrdName);
this.start();
}
public void run() {
int i=0;
while (true) {
System.out.println(thrdName + ":" + i);
i++;
if (i>num) {
System.out.println(thrdName + " over.");
break;
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
=======================================================
Test.java
/**
* 在主线程中使用join等待所有子线程执行结束。
* 主线程,在所有子线程开始前做初始化处理,在所有子线程结束后做资源回收处理。
*
*/
public class Test {
public static void main(String[] args) {
while(true) {
init();//初始化处理
handle();//调用线程类进行业务逻辑处理,此方法在执行过程中会挂起,直到所有线程类执行结束
destroy();//资源回收
}
}
private static void init() {
System.out.println("######### open resource");
}
private static void handle() {
int num = 3;
MyThread[] thrdArr = new MyThread[num];
for (int i=0; i<num; i++) {
MyThread thrd = new MyThread("name" + i);
thrdArr[i] = thrd;
}
for (int i=0; i<num; i++) {
MyThread thrd = thrdArr[i];
try {
System.out.println("---" + thrd.getName() + " join before");
thrd.join();//阻塞,直到子线程结束。注意:子线程必须有可以退出的条件。
System.out.println("---" + thrd.getName() + " join after");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static void destroy() {
System.out.println("######### release resource");
}
}