首页 > 代码库 > Java中线程等待(同步)的五种方法

Java中线程等待(同步)的五种方法

在面试时,经常会有面试官问道,一个主线程有多个子线程,如何能使子线程的业务执行完成之后,再执行主线程业务逻辑。对于这个问题,本人能够想到的有五种方法,详细请移步源码

1、使用线程类自带的join方法,将子线程加入到主线程,在子线程执行完之后,在执行主线程逻辑。

例如

public static void joinDemo()
        throws InterruptedException
    {
        System.out.println("=========Test with join=====");
        JoinWorker worker1 = new JoinWorker("worker1");
        JoinWorker worker2 = new JoinWorker("worker2");
        worker1.start();
        worker2.start();
        worker1.join();
        worker2.join();
        doSuperWork();
    }

2、使用JDK的并发包中的CountDownLatch类, 使用CountDownLatch,每个线程调用其countDown方法使计数器-1,主线程调用await方法阻塞等待,直到CountDownLatch计数器为0时继续执行,例如

首先,定义子线程

static class CountDownLatchWorker extends Thread
    {
        String workerName;

        CountDownLatch latch;

        public CountDownLatchWorker(String workerName, CountDownLatch latch)
        {
            this.workerName = workerName;
            this.latch = latch;
        }

        public void run()
        {
            System.out.println("Sub Worker " + workerName + " do work begin at "
                               + sdf.format(new Date()));
            new ThreadWaitDemo().doSomeWork();// 做实际工作
            System.out.println("Sub Worker " + workerName + " do work complete at "
                               + sdf.format(new Date()));
            latch.countDown();// 完成之后,计数器减一

        }
    }

主线程中调研await方法阻塞等待,直到所有线程完成

public static void countDownLatchDemo()
        throws InterruptedException
    {
        System.out.println("=========Test with CountDownLatch=====");
        CountDownLatch latch = new CountDownLatch(2);
        CountDownLatchWorker worker1 = new CountDownLatchWorker("worker1", latch);
        CountDownLatchWorker worker2 = new CountDownLatchWorker("worker2", latch);
        worker1.start();
        worker2.start();
        //主线程阻塞等待
        latch.await();
        doSuperWork();
    }

3、使用JDK并发包CyclicBarrier,CyclicBarrier类似于CountDownLatch也是个计数器, 不同的是CyclicBarrier的await()方法没被调用一次,计数便会减少1,并阻塞住当前线程。当计数减至0时,阻塞解除,所有在此 CyclicBarrier 上面阻塞的线程开始运行。 在这之后,如果再次调用 await()方法,计数就又会变成 N-1,新一轮重新开始CyclicBarrier初始时还可带一个Runnable的参数,此Runnable任务在CyclicBarrier的数目达到后,所有其它线程被唤醒前被执行。

示例如下

public static void cyclicBarrierDemo()
        throws InterruptedException, BrokenBarrierException
    {
        System.out.println("=========Test with CyclicBarrier=====");
        CyclicBarrier cb = new CyclicBarrier(2, new Runnable()
        {
            // 将主线程业务放到CyclicBarrier构造方法中,所有线程都到达Barrier时执行
            @SuppressWarnings("static-access")
            public void run()
            {
                new ThreadWaitDemo().doSuperWork();
            }
        });// 设定需要等待两个线程
        ExecutorService executor = Executors.newFixedThreadPool(2);
        CyclicBarrierWorker worker1 = new CyclicBarrierWorker("worker1", cb);
        CyclicBarrierWorker worker2 = new CyclicBarrierWorker("worker2", cb);
        executor.execute(worker1);
        executor.execute(worker2);
        executor.shutdown();
    }

4、使用JDK并发包中的Executors框架,ExecutorService的的invokeAll方法调研callable集合,批量执行多个线程,在invokeAll方法结束之后,再执行主线程其他业务逻辑

示例如下

public static void callableDemo()
        throws InterruptedException
    {
        System.out.println("=========Test with Callable=====");
        List<Callable<Integer>> callList = new ArrayList<Callable<Integer>>();
        ExecutorService exec = Executors.newFixedThreadPool(2);
        // 采用匿名内部类实现
        callList.add(new Callable<Integer>()
        {
            public Integer call()
                throws Exception
            {
                System.out.println("Sub Worker worker1 do work begin at " + sdf.format(new Date()));
                new ThreadWaitDemo().doSomeWork();// 做实际工作
                System.out.println("Sub Worker worker1 do work complete at "
                                   + sdf.format(new Date()));
                return 0;
            }
        });
        callList.add(new Callable<Integer>()
        {
            public Integer call()
                throws Exception
            {
                System.out.println("Sub Worker worker2 do work begin at " + sdf.format(new Date()));
                new ThreadWaitDemo().doSomeWork();// 做实际工作
                System.out.println("Sub Worker worker2 do work complete at "
                                   + sdf.format(new Date()));
                return 0;
            }
        });
        exec.invokeAll(callList);
        exec.shutdown();
        doSuperWork();

    }
5、这种过于恶心,只简单说一下方法,主线程创建一个线程List,将每个子线程保存到列表中,然后定期轮询列表中子线程状态,当所有线程都完成之后,再执行主线程逻辑


Java中线程等待(同步)的五种方法