Java中的多线程线程作业
我想在Java中同时产生200个线程。我现在正在做的是运行一个循环,创建200个线程并启动它们。在这200个线程完成后,我想再生成200组线程,以此类推
这里的要点是,我生成的前200个线程需要在生成下一组之前完成。我尝试了下面的代码,但它不起作用
for(int i=0;i<200;i++){
Thread myThread = new Thread(runnableInstance);
myThread.start();
}
for(int i=0;i<200;i++){
Thread myThread = new Thread(runnableInstance);
myThread.start();
}
注意:我有意将for循环放了两次,但我想要的效果不会发生,因为第二个for循环是在第一组线程结束执行之前执行的
请告知
# 1 楼答案
您应该保留已创建线程的列表。然后,一旦启动了所有列表,就可以在列表上循环并对每个列表执行
join
。当连接循环完成时,所有线程都将运行到完成# 2 楼答案
您需要使用
join()
等待线程完成:# 3 楼答案
如果您使用的是Java1.5,那么就使用并发包,如果您使用的是Java1.4.2,那么这个包仍然可以作为一个后端口使用,我非常确定
尽管如此,我最近也有类似的任务要做;通过使用ExecutorService来了解任务是否完成,可以非常轻松地实现这一点。非常干净的模式-可能不完全是您想要实现的,但在现实生活中它工作得非常好:-)
一些代码:
# 4 楼答案
感觉像是在做家务,但是
# 5 楼答案
另一个解决方案是使用闩锁
# 6 楼答案
某种伪代码,您可以调用acnt实例;-)