线程同步控制

Posted 水田如雅

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程同步控制相关的知识,希望对你有一定的参考价值。

CyclicBarrier

int iMax = 100;
    CyclicBarrier barrier = new CyclicBarrier(iMax);
    int shareValue = 0;
    Lock lock = new ReentrantLock();
    @Test
    public void test() throws Exception 
        for (int i = 0; i < iMax; i++) 
            SomeProcessValue t = new SomeProcessValue();
            t.start();
        
        barrier.await();
        System.out.println(shareValue);
    

    public class SomeProcessValue extends Thread 
        @Override
        public void run() 
            try 
                Thread.sleep(new Random().nextInt(10));
                lock.lock();
                shareValue++;
                lock.unlock();
                barrier.await();
             catch (Exception e) 
                e.printStackTrace();
            
        
    

Semaphore & CountDownLatch

  int value = 0;
    @Test
    public void test4() throws InterruptedException 
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CountDownLatch counter = new CountDownLatch(10);
        Semaphore semaphore = new Semaphore(1); //信号量控制只有一个线程
        for (int i = 0; i < 10; i++) 
            executorService.submit(() -> 
                try 
                    semaphore.acquire();
                    Thread.sleep(1000);
                 catch (InterruptedException e) 
                    e.printStackTrace();
                
                counter.countDown();
                value++;
                System.out.println(value);
                semaphore.release();
            );
        
        counter.await();
    

Exchanger

@Test
    public void test1() 
        Exchanger<String> exchanger = new Exchanger<>();
        ExecutorService executorService = Executors.newFixedThreadPool(2);
        executorService.execute(() -> 
            try 
                System.out.println(exchanger.exchange("t1888888"));
                ;
             catch (Exception e) 
                e.printStackTrace();
            

        );
        executorService.execute(() -> 
            try 
                System.out.println("t2---" + exchanger.exchange("t2"));
             catch (Exception e) 
                e.printStackTrace();
            
        );
        executorService.shutdown();
    

以上是关于线程同步控制的主要内容,如果未能解决你的问题,请参考以下文章

实验十七 线程同步控制

起底多线程同步锁(iOS)

ReentrantReadWriteLock场景应用

多线程的同步

多线程编程

在控制台应用程序中,为啥在等待的异步任务中使用同步阻塞代码 (Thread.Sleep(..)) 的行为类似于多线程? [复制]