线程同步控制

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();
    

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

线程的几个主要概念----线程间通信;线程死锁;线程控制:挂起停止和恢复(线程同步的5种方式)

信号量 也是同步锁,可用来控制线程的并发数

从网易的一道多线程笔试题学习wait与notify来控制线程同步

线程的同步控制(Synchronization)

线程同步控制

线程同步控制