Cyclicbarrier source code analysis – java8

1. Characteristic analysis

Private static class generation class has only one domain, Boolean broken = false; Used to identify whether the current barrier is in broken status. private final reentrantlock lock = new reentrantlock(); Private final condition trip = lock newCondition(); Waiting conditions before trip Private Final int parties; Number of threads using this barrier at the same time private final runnable barriercommand; When trip, the barrier operation defined by barrier private Generation generation = new Generation(); Current generation private int count; Number of waiting threads. On each generation, the count value will be reduced from parties to 0. For each new generation or when the current barrier is broken, the count value will be reset. Two construction methods: public cyclicbarrier (int parties) public cyclicbarrier (int parties, runnable barrieraction) private int dowait (Boolean timed, long nanos) method. This method is the main code of the barrier, which includes many implementation strategies of classes Await () method calls this method directly. Execution process: method to lock: dowait(), isbroken(), reset(), getnumberwaiting().

package sourcecode. analysis;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Main {

static Runnable action = () -> System.out.println("this is action");
static CyclicBarrier cb = new CyclicBarrier(2,action);

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

Runnable r1 = () -> {
    try {
        cb.await();
    } catch (InterruptedException e) {

    } catch (BrokenBarrierException e) {

    }

    Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println("this is thread1");

};
Runnable r2 = () -> {
    try {
        cb.await();
    } catch (InterruptedException e) {

    } catch (BrokenBarrierException e) {

    }
    Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println("this is thread2");
};

Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
Sy<a href="https://www.jb51.cc/tag/stem/" target="_blank" class="keywords">stem</a>.out.println("this is main thread");

}

}

Output results

this is main thread
this is action
this is thread2
this is thread1

perhaps

this is action
this is main thread
this is thread1
this is thread2  

perhaps

this is main thread
this is action
this is thread1
this is thread2
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>