使用wait和AtomicInteger进行线程运行结束统计
作者:bin如何在所有子线程执行完后,才继续执行主线程?
思路是:统计执行完的子线程,再继续执行父线程
public class thread {
    public static final String monitor = "100";
    public static void main(String[] args) throws Exception{
        AtomicInteger count = new AtomicInteger(10);
        IntStream.range(0,10).boxed().forEach(integer -> {
            new Thread(()->{
                System.out.println("子线程开始睡觉,线程数" + integer);
                try {
                    TimeUnit.SECONDS.sleep(5);
                    System.out.println("子线程醒了" + integer);
                    count.decrementAndGet();
                    if (count.get() == 0){
                        synchronized (monitor){
                            monitor.notify();
                        }
                    }
                }catch (Exception e){
                    System.out.println("子线程被打断" + integer);
                }
            }).start();
        });
        System.out.println("主线程开始等待");
        synchronized (monitor){
            monitor.wait();
        }
        System.out.println("主线程被唤醒");
    }
}