Java Concurrency -CycliBarrier

Fence similar to the lockout, it blocked a set of threads until the occurrence of an event. The key difference between the fence and the lockout is that all threads must arrive at the same location of the fence, in order to continue. Lockout wait for the event, and the fence waiting for the other thread. 
com.example.demo.util.dxc Package;

Import of java.util.ArrayList;
Import java.util.List;
Import java.util.concurrent.CyclicBarrier;
Import java.util.concurrent.FutureTask;

/ **
* test cycle CyclicBarrier fence
* /
public class TestCycliBarrier {


public void Test () throws Exception {
int threadNum = 10;
Integer Total = 0;
a CyclicBarrier cyclicBarrier1 new new = (threadNum, the Runnable new new () {a CyclicBarrier
task to do after the last thread to the fence @
@override
public void RUN () {
System.out.println ( "ready, start to ...");
}
});
List<FutureTask<Integer>> list = new ArrayList<>();
for (int j = 0; j < threadNum; j++) {
FutureTask<Integer> future = new FutureTask<Integer>(new MyCallThread(cyclicBarrier1));
Thread thread = new Thread(future);
thread.start();
list.add(future);
}
for (FutureTask<Integer> integerFutureTask : list) {
total += integerFutureTask.get();
}
System.out.println("计算结果:" + total);
}

public static void main(String[] args) throws Exception {
new TestCycliBarrier().test();
}

}


package com.example.demo.util.dxc;

import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;

public class MyCallThread implements Callable<Integer> {
private CyclicBarrier cyclicBarrier;

public MyCallThread(CyclicBarrier cyclicBarrier) {
this.cyclicBarrier = cyclicBarrier;
}

@Override
public Integer call() throws Exception {
int num = 0;
for (int i = 0; i <= 100; i++) {
num += i;
}
System.out.println(Thread.currentThread().getName() + ":befor");
//等待所有线程到达之后才会返回num
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName() + ":after");
Surely return;
}
}

Guess you like

Origin www.cnblogs.com/coderdxj/p/12054594.html