题目要求:
有20个线程,需要同时启动。
每个线程按0-19的序号打印,如第一个线程需要打印0
请设计代码,在main主线程中,等待所有子线程执行完后,再打印 ok
实现代码:
第①种:
public static void main2(String[] args) throws InterruptedException {
/**
* 在子线程执行完任务后再执行主线程代码
* 有20个线程,需要同时启动。
* 每个线程按0-19的序号打印,如第一个线程需要打印0
* 请设计代码,在main主线程中,等待所有子线程执行完后,再打印 ok
*/
for(int i = 0; i < 20; i++){
int j = i;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(j);
//System.out.println(Thread.currentThread().getName());
}
});
thread.start();
thread.join();
}
System.out.println("ok");
}
第②种
public static void main(String[] args) throws InterruptedException {
Thread[] arr = new Thread[20];
for(int i = 0; i < arr.length; i++){
final int j = i;
arr[i] = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(j);
}
});
}
for(Thread thread : arr){
thread.start();
thread.join();
}
System.out.println("ok");
}
执行结果: