zoukankan      html  css  js  c++  java
  • java并发编程(Exchanger)

    package org.bianqi.demo1;
    
    import java.util.concurrent.Exchanger;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class Demo3 {
    	public static void main(String[] args) throws InterruptedException, TimeoutException {
    		ExecutorService service = Executors.newCachedThreadPool();
    		final Exchanger<String> exchanger = new Exchanger<>();
    		service.execute(new Runnable() {
    			public void run() {
    				String data1 = "毒品";
    				System.out.println("毒贩子带着"+data1+"出发了");
    				try {
    					Thread.sleep((long) (Math.random()*1000));
    					String exchange = exchanger.exchange(data1,2, TimeUnit.SECONDS);
    					System.out.println("毒贩子把"+exchange+"带走了");
    				} catch (InterruptedException | TimeoutException e) {
    					e.printStackTrace();
    				}
    			}
    		});
    		
    		service.execute(new Runnable() {
    			public void run() {
    				String  data2 ="人民币";
    				System.out.println("瘾君子带着"+data2+"出发了");
    				try {
    					Thread.sleep((long) (Math.random()*1000));
    					String exchange = exchanger.exchange(data2, 2, TimeUnit.SECONDS);
    					System.out.println("瘾君子把"+exchange+"带走了");
    				} catch (InterruptedException | TimeoutException e) {
    					e.printStackTrace();
    				}
    			}
    		});
    		service.shutdown();
    	}
    }
    

      

  • 相关阅读:
    c++ 01
    unix c 11
    unix c 10
    unix c 09
    unix c 08
    unix c 07
    unix c 06
    unix c 05
    unix c 04
    Petrozavodsk Summer Training Camp 2017
  • 原文地址:https://www.cnblogs.com/bianqi/p/6640546.html
Copyright © 2011-2022 走看看