[do level 1]
我建议你分两个街区分手[do level 2]
。
就像是
...
for(int i=0; i< 10; i++)
{
new Thread(){
public void run(){
<do something level 1>
}
}.start;
}
**join**
for(int i=0; i< 10; i++)
{
new Thread(){
public void run(){
<do something level 2>
}
}.start;
}
<do something level 3>
...
而不是在主线程中使用带有计数器的wait
\ 。notify
可能只是因为我对这些不满意,但我相信这会使事情变得不必要地复杂,你几乎肯定会遇到竞争条件。
此外,我建议您使用ExecutorService
抽象而不是使用Thread
s. 它们消除了在最低级别工作的需要,并且可配置性强且功能强大。一旦你习惯了它们,它们也更容易理解。
ExecutorService service = Executors.newFixedThreadPool(10);
for (int i = 1; i <= 10; i++) {
final int w = i;
service.execute(new Runnable() {
public void run() {
long wait = (long) (Math.random() * 1000);
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
}
System.out.println(w + "LEVEL 1 done " + wait);
}
});
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
System.out.println("all level 1 done");
service = Executors.newFixedThreadPool(10);
for (int i = 1; i <= 10; i++) {
final int w = i;
service.execute(new Runnable() {
public void run() {
long wait = (long) (Math.random() * 1000);
try {
Thread.sleep(wait);
} catch (InterruptedException e) {
}
System.out.println(w + "LEVEL 2 done " + wait);
}
});
}
service.shutdown();
service.awaitTermination(1, TimeUnit.DAYS);
System.out.println("all done");