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();
    	}
    }
    

      

  • 相关阅读:
    18、led驱动程序的实现
    17、字符设备控制技术
    16、驱动访问大揭秘
    14、字符驱动编程模型
    个人开发—进度记录(一)
    个人开发—需求
    学习进度条
    敏捷开发第二阶段个人(七)
    敏捷开发第二阶段个人(六)
    敏捷开发第二阶段个人(五)
  • 原文地址:https://www.cnblogs.com/bianqi/p/6640546.html
Copyright © 2011-2022 走看看