Java Multithreading and Concurrency Library Advanced Application--16

Java
Multithreading

2018-5- 5 16.52




package cn.itcast.heima2;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class CountdownLatchTest {


public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1);
final CountDownLatch cdAnswer = new CountDownLatch(3);for(int i=0;i<3;i++){Runnable runnable = new Runnable(){public void run(){try {System.out.println("线程" + Thread.currentThread().getName() + "正准备接受命令");cdOrder.await();







System.out.println("Thread" + Thread.currentThread().getName() + 
"Command accepted"); Thread.sleep((long)(Math.random()*10000)); System.out.println ("Thread" + Thread.currentThread().getName() +  "Response command processing result"); cdAnswer.countDown(); } catch (Exception e) { e.printStackTrace(); } } }; service.execute( runnable); } try { Thread.sleep((long)(Math.random()*10000)); System.out.println("Thread" + Thread.currentThread().getName() +  "Comment to be issued") ; cdOrder.countDown();// One is ready, execute System.out.println("Thread" + Thread.currentThread().getName() +  "Command sent, waiting for result"); cdAnswer. await();// Three are here, continue to execute




















System.out.println("Thread" + Thread.currentThread().getName() + 
"All response results have been received"); } catch (Exception e) { e.printStackTrace(); } service.shutdown(); } }










Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325729271&siteId=291194637