当前位置: 代码迷 >> Exchange >> Exchanger关于互换情报的例子
  详细解决方案

Exchanger关于互换情报的例子

热度:7200   发布时间:2013-02-26 00:00:00.0
Exchanger关于交换情报的例子
package com.test;import java.util.Random;import java.util.concurrent.Exchanger;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class ExchangerTest{	/**	 * @param args	 */	public static void main(String[] args)	{		ExecutorService pool = Executors.newCachedThreadPool();		final Exchanger changer = new Exchanger();		pool.execute(new Runnable()		{			public void run()			{				String data1 = "情报1";				System.out.println("线程:" + Thread.currentThread().getName()						+ "准备把:" + data1+"交换出去");				try				{					Thread.sleep(new Random().nextInt(10000));					String data2 = (String)changer.exchange(data1);					System.out.println("线程:" + Thread.currentThread().getName()							+ "获得了:" + data2);				}				catch (Exception e)				{					e.printStackTrace();				}			}		});				pool.execute(new Runnable()		{			public void run()			{				String data1 = "情报2";				System.out.println("线程:" + Thread.currentThread().getName()						+ "准备把:" + data1+"交换出去");				try				{					Thread.sleep(new Random().nextInt(10000));					String data2 = (String)changer.exchange(data1);					System.out.println("线程:" + Thread.currentThread().getName()							+ "获得了:" + data2);				}				catch (Exception e)				{					e.printStackTrace();				}			}		});				pool.shutdown();	}}