The Java parent of or the main thread waits for an instance where all the child threads exit
- 2020-11-20 06:06:27
- OfStack
Examples are as follows:
static void testLock1(){
final AtomicInteger waitCount = new AtomicInteger(30000);
final Object waitObj = new Object();
System.out.println("start"+System.currentTimeMillis());
for (int i=0;i<30000;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitCount.decrementAndGet();
synchronized(waitObj){
waitObj.notifyAll();
}
}
}).start();
}
while( waitCount.intValue()>0) {
synchronized (waitObj) {
if(waitCount.intValue()>0){
try {
waitObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
System.out.println("ok"+System.currentTimeMillis());
}
static void testLock2(){
final CountDownLatch workLauch = new CountDownLatch(30000);// counter
System.out.println("start2"+System.currentTimeMillis());
for (int i=0;i<30000;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
workLauch.countDown();
}
}).start();
}
try {
workLauch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("ok2"+System.currentTimeMillis());
}
public static void main(String[] args) {
testLock1();
testLock2();
}
The first one is the implementation that I just wrote here, which is kind of rough. The second is a friend notifies you of a class, java's concurrent, which is said to have several similar functional class implementations. The 30,000 threads time difference is probably less than 200ms