JDK1.5 Exchange 두 스레드 교환 데이터

2469 단어 exchange
자세히 보기


import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Exchange 2  
 */
public class ExchangeTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ExecutorService service=Executors.newCachedThreadPool();
		final Exchanger exchanger=new Exchanger();
		service.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String data1="zxx";
					System.out.println(" "+Thread.currentThread().getName()+" "+data1+" ");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println(" "+Thread.currentThread().getName()+" "+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			
		});
		
		
		service.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String data1="lhm";
					System.out.println(" "+Thread.currentThread().getName()+" "+data1+" ");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println(" "+Thread.currentThread().getName()+" "+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
			
		});
		
		service.execute(new Runnable(){
			@Override
			public void run() {
				try {
					String data1="happy";
					System.out.println(" "+Thread.currentThread().getName()+" "+data1+" ");
					Thread.sleep((long)Math.random()*10000);
					String data2=(String)exchanger.exchange(data1);
					System.out.println(" "+Thread.currentThread().getName()+" "+data2);
				} catch (Exception e) {
					// TODO: handle exception
				}
				
			}
			
		});

	}
}

결과:
스레드pool-1-thread-1 데이터 zxx를 바꾸고 있습니다.
스레드pool-1-thread-2 데이터를 lhm로 바꾸고 있습니다.
스레드 풀-1-thread-3 데이터를 happy로 바꾸고 있습니다.
스레드pool-1-thread-3 교환된 데이터는 zxx
스레드pool-1-thread-1 변환된 데이터는happy

좋은 웹페이지 즐겨찾기