Java Exchanger 学习笔记

今天学习了一下Exchanger. 可以让一对线程交换数据,模拟了一个场景,标记一下,方便以后查看。

 

package multithread.exchanger;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Exchanger;

/**
 * 兑换奖品
 * 
 * @author lemzhang
 * 
 */
public class TestExchanger {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final TestExchanger t = new TestExchanger();
		final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(5);
		final Exchanger<String> exchanger = new Exchanger<String>();
		for (int i = 0; i < 5; i++) {
			queue.offer("5角现金.");
		}
		t.exchange(exchanger, queue);
	}

	public void exchange(Exchanger<String> exchanger,
			BlockingQueue<String> queue) {
		new Thread(new Agent(exchanger, queue), "代理商").start();
		new Thread(new Customer(exchanger), "消费者").start();
	}

	class Customer implements Runnable {
		private final Exchanger<String> exchanger;

		public Customer(Exchanger<String> exchanger) {
			this.exchanger = exchanger;
		}

		@Override
		public void run() {
			String s = "5角的瓶盖";
			String printStr = "[%s]我收集到一个中5角的瓶盖, 代理商给我兑换了%s \n";
			for (int i = 0; i < 10; i++) {
				try {
					String ex = exchanger.exchange(s);
					if (!ex.equals("5角现金."))
						printStr = "[%s]我收集到一个中5角的瓶盖, 但是 %s \n";
					System.out.printf(printStr, Thread.currentThread()
							.getName(), ex);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

	class Agent implements Runnable {
		private final Exchanger<String> exchanger;
		private final BlockingQueue<String> q;

		public Agent(Exchanger<String> exchanger, BlockingQueue<String> q) {
			this.exchanger = exchanger;
			this.q = q;
		}

		@Override
		public void run() {
			String printStr = "[%s]用[%s]兑换消费者的瓶盖:[%s] \n";
			for (int i = 0; i < 8; i++) {
				String award = q.poll();
				if (award == null) {
					award = "奖品兑完了,请下次再来.";
					printStr = "[%s]奖品库存没了,没有给消费者兑换\n";
				}
				try {
					System.out.printf(printStr, Thread.currentThread()
							.getName(), award, exchanger.exchange(award));
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}

 

你可能感兴趣的:(Java 多线程 同步器)