package com.citi.icg.ddi.client.service.test;
import java.util.ArrayList;
import java.util.List;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
List<SubThread> threads = new ArrayList<SubThread>();
for (int i = 0; i < 10; i++) {
SubThread thread = new SubThread(i);
threads.add(thread);
thread.start();
}
// 主线程处理其他工作,让子线程异步去执行.
mainThreadOtherWork();
System.out.println("now waiting sub thread done.");
// 主线程其他工作完毕,等待子线程的结束, 调用join系列的方法即可(可以设置超时时间)
try {
for (Thread t : threads) {
t.join();// main 线程挂起直到目标线程t结束才恢复(thread.isAlive() return false)
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("now all done.");
}
private static void mainThreadOtherWork() {
System.out.println("main thread work start");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread work done.");
}
public static class SubThread extends Thread {
int i;
public SubThread(int i) {
this.i = i;
this.setName("Thread" + i);
}
@Override
public void run() {
working();
}
private void working() {
System.out.println(i + "sub thread start working.");
busy();
System.out.println(i + "sub thread stop working.");
}
private void busy() {
try {
sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
import java.util.ArrayList;
import java.util.List;
public class ThreadTest {
/**
* @param args
*/
public static void main(String[] args) {
List<SubThread> threads = new ArrayList<SubThread>();
for (int i = 0; i < 10; i++) {
SubThread thread = new SubThread(i);
threads.add(thread);
thread.start();
}
// 主线程处理其他工作,让子线程异步去执行.
mainThreadOtherWork();
System.out.println("now waiting sub thread done.");
// 主线程其他工作完毕,等待子线程的结束, 调用join系列的方法即可(可以设置超时时间)
try {
for (Thread t : threads) {
t.join();// main 线程挂起直到目标线程t结束才恢复(thread.isAlive() return false)
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("now all done.");
}
private static void mainThreadOtherWork() {
System.out.println("main thread work start");
try {
Thread.sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main thread work done.");
}
public static class SubThread extends Thread {
int i;
public SubThread(int i) {
this.i = i;
this.setName("Thread" + i);
}
@Override
public void run() {
working();
}
private void working() {
System.out.println(i + "sub thread start working.");
busy();
System.out.println(i + "sub thread stop working.");
}
private void busy() {
try {
sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}