Concurrency control class of Java concurrent programming

CountDownLatch

Allow one or more threads to wait for other threads to complete the operation.    

public static void main(String[] args) throws InterruptedException {

     final CountDownLatch c = new CountDownLatch(2);

        new Thread(new Runnable() {

            @Override

            public void run() {

                c.countDown();

                System.out.println("线程1执行完成");

            }

        }).start();

        new Thread(new Runnable() {

         @Override

         public void run() {

         c.countDown();

         System.out.println("线程2执行完成");

         }

        }).start();


        c.await();

        System.out.println("退出");

}

result:

Thread 1 execution completed

Thread 2 execution completed

drop out

 

The constructor of CountDownLatch receives one, where the construction parameter n means waiting for n completion, that is, execute countDown n times.

CyclicBarrier

A group of threads are blocked when they reach a barrier (also called a synchronization point), until the last thread reaches the barrier    

public static void main(String[] args) {

        new Thread(new Runnable() {


            @Override

            public void run() {

                try {

                    c.await();

                } catch (Exception e) {


                }

                System.out.println(1);

            }

        }).start();


        try {

            c.await();

        } catch (Exception e) {


        }

        System.out.println(2);

}

When two threads execute c.await(), it means that the current barrier intercepts two threads. Compare the CyclicBarrier interception parameters. If the synchronization standard has been reached, the two threads continue to execute, for example: new CyclicBarrier(2); if count! =0, the two threads continue to wait.

Source code analysis:    

public CyclicBarrier(int parties, Runnable barrierAction) {

        if (parties <= 0) throw new IllegalArgumentException();

//在barrier被触发之前必须调用的线程数

        this.parties = parties;

        this.count = parties;

//在barrier被触发时调用action

        this.barrierCommand = barrierAction;

    }

    public CyclicBarrier(int parties) {

        this(parties, null);

}

    public int await() throws InterruptedException, BrokenBarrierException {

        try {

            return dowait(false, 0L);

        } catch (TimeoutException toe) {

            throw new Error(toe); // cannot happen

        }

    }

}

private int dowait(boolean timed, long nanos)

        throws InterruptedException, BrokenBarrierException,

               TimeoutException {

//.....

int index = --count;

            if (index == 0) {  // tripped

//....

nextGeneration();

return 0;

//....

}

trip.await();

//.....

}

    private void nextGeneration() {

        // signal completion of last generation

        trip.signalAll();

        // set up next generation

        count = parties;

        generation = new Generation();

}

Here is only a brief analysis.

Semaphore

Semaphore (semaphore) is used to control the number of threads that access specific resources at the same time. It coordinates various threads to ensure the reasonable use of common resources.

Semaphore's construction method Semaphore (int permits) accepts an integer number that represents the number of licenses available. Semaphore (10) means that 10 threads are allowed to obtain a license, that is, the maximum concurrent number is 10.

Semaphore's acquire() method acquires a license, and then calls the release() method to return the license after use. You can also try to acquire a license with the tryAcquire() method.    

public static void main(String[] args) {

     ExecutorService threadPool   = Executors.newFixedThreadPool(10);

     final Semaphore       s            = new Semaphore(5);

        for (int i = 0; i < 30; i++) {

            threadPool.execute(new Runnable() {

                @Override

                public void run() {

                    try {

                        s.acquire();

                        System.out.println("save data");

                        s.release();

                    } catch (InterruptedException e) {

                    }

                }

            });

        }


        threadPool.shutdown();

}

Analysis: The maximum number of threads in the current thread pool is 10, the tasks that need to be executed are 30, and the permitted size of tasks to be executed at the same time is 5. That is to say, the concurrency of task execution is affected by the number of threads and permissions. Although the number of threads is 10, only 5 tasks can be executed at the same time.

 

Other methods of Semaphore:

Int availablePermits(): Returns the number of licenses currently available in this semaphore.

Int getQueueLength(): Returns the number of threads waiting to obtain a license.

Boolean hasQueuedThreads(): Whether any threads are waiting to obtain a license.

void reducePermits (int reduction): Reduce reduction permits, which is a protected method.

Collection getQueuedThreads(): Returns the collection of all threads waiting to obtain a license. It is a protected method.

Exchanger

Exchanger (Exchanger) is a tool class for collaboration between threads. Exchanger is used for data exchange between threads. It provides a synchronization point at which two threads can exchange data with each other. The two threads exchange data through the exchange method. If the first thread executes the exchange() method first, it will always wait for the second thread to execute the exchange method. When both threads reach the synchronization point, the two threads will You can exchange data and pass the data produced by this thread to the other party.

public static void main(String[] args) {

final Exchanger<String> exgr = new Exchanger<String>();

ExecutorService threadPool = Executors.newFixedThreadPool(2);

threadPool.execute(new Runnable() {

@Override

public void run() {

try {

String A = "银行流水A";// A录入银行流水数据

exgr.exchange(A);

} catch (InterruptedException e) {

}

}

});


threadPool.execute(new Runnable() {

@Override

public void run() {

try {

String B = "银行流水B";// B录入银行流水数据

String A = exgr.exchange("B");

System.out.println("A和B数据是否一致:" + A.equals(B) + ",A录入的是:" + A + ",B录入是:" + B);

} catch (InterruptedException e) {

}

}

});


threadPool.shutdown();


}

 

 

Guess you like

Origin blog.csdn.net/weixin_44416039/article/details/86162827