本文主要是介绍java并发编程实战-CyclicBarrier和FutureTask使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import java.util.concurrent.Callable;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.FutureTask;public class FutureTest {public static void main(String[] args) {new FutureTest().test();}public void test() {// 设置7个线程栅栏,为什么6个线程要设置7个栅栏,因为需要阻塞本线程等待6个线程的执行结果final CyclicBarrier cb = new CyclicBarrier(7);// 创建6个服务final Service[] assembles = new Service[6];final FutureTask[] futureTasks = new FutureTask[6];final Domain domain = new Domain();assembles[0] = new Service0();assembles[1] = new Service1();assembles[2] = new Service2();assembles[3] = new Service3();assembles[4] = new Service4();assembles[5] = new Service5();for(int i = 0; i < 6; i++) {final int fi = i;futureTasks[i] = new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { try {assembles[fi].assemble(domain);System.out.println(fi + "assemble");} finally {cb.await();}return fi;} });new Thread(futureTasks[i]).start(); }try {cb.await();} catch (Exception e) {System.err.println(e);}for(int i = 0; i < 6; i++) {try {System.out.println(futureTasks[i].get());} catch (Exception e) {// 获取Service5抛出的异常System.err.println(e);} }System.out.println(domain);}interface Service {void assemble(Domain domian);}class Domain{public String t0;public String t1;public String t2;public String t3;public String t4;@Overridepublic String toString() {return t0 + "-" +t1 + "-" +t2 + "-" +t3 + "-" + t4;}}class Service0 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(2000);} catch (InterruptedException e) {System.err.println(e);}domian.t0 = "0";}}class Service1 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(4000);} catch (InterruptedException e) {System.err.println(e);}domian.t1 = "1";}}class Service2 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(2000);} catch (InterruptedException e) {System.err.println(e);}domian.t2 = "2";}}class Service3 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(3000);} catch (InterruptedException e) {System.err.println(e);}domian.t3 = "3";}}class Service4 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(1000);} catch (InterruptedException e) {System.err.println(e);}domian.t4 = "4";}}class Service5 implements Service {@Overridepublic void assemble(Domain domian) {try {Thread.sleep(5000);} catch (InterruptedException e) {System.err.println(e);}throw new RuntimeException();}}
}
这篇关于java并发编程实战-CyclicBarrier和FutureTask使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!