比如有一个main线程。
在main thread中产生一个子线程subThread,当在subThread.start()之后 若再用subThread.join()方法会产生这样的效果:
main thread会暂时block住,直到subThread结束。 这个大家都知道。我想问,
如果我在main thread中需要产生5个subThread,这5个subThread我希望他们交替运行并且在他们运行的过程中main thread需要被block住。最后当5个subThread都结束的时候,main thread继续运行。 请问如何实现?
在main thread中产生一个子线程subThread,当在subThread.start()之后 若再用subThread.join()方法会产生这样的效果:
main thread会暂时block住,直到subThread结束。 这个大家都知道。我想问,
如果我在main thread中需要产生5个subThread,这5个subThread我希望他们交替运行并且在他们运行的过程中main thread需要被block住。最后当5个subThread都结束的时候,main thread继续运行。 请问如何实现?
for(int i = 0; i < count; i++)
t[i].join();
就可以了,自然会等待所有的线程结束。
public class Join {
public static void main(String[] args) throws InterruptedException {
System.out.println("main start");
// for(int i=0; i<5; i++){
// Thread t = new Thread(new Threads(i));
// t.start();
// t.join(); //这样直接start后就join,这些不会交替运行
// }
Thread[] threads = new Thread[5];
for(int i=0; i<5; i++){
Thread t = new Thread(new Threads(i));
t.start();
threads[i] = t;
}
for(int j=0; j<threads.length; j++){
threads[j].join();
}
System.out.println("main end");
}}
class Threads implements Runnable{
int id;
public Threads(int i){
this.id = i;
}
public void run() {
// TODO Auto-generated method stub
for(int i=0; i<10; i++){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("---- Thread"+id);
}
}
}
for(int i=0; i<5; i++){
Thread t = new Thread(new Threads(i));
t.start();
threads[i] = t;
}
for(int j=0; j<threads.length; j++){
threads[j].join();
}
5个subThread都join()2.条件一:5个subThread交替执行
在五个subThread中共享同一个执行的互斥的锁不就好了?
这种实现貌似很简单。
如果要看代码的话,你借鉴Timer的中的任务队列中任务执行互斥的写法就好了。