多线程之Exchanger


package com.test6;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Exchanger;
 
/**
 * Exchanger这个类,估计大家是很少用到,笔者最近在项目也用到这个类,在项目使用这个类来用于两个线程进行交换数据缓存,
 * 比如一个线程来读数据,另一个线程在写入缓存,在这两个线程中用Exchanger进行交换数据.接下来我写了一段代码来说明这个类的使用场景:
 *
 */
public class ExchangerTest {
 
	public static void main(String[] args) {
		Exchanger<List<String>> exchanger = new Exchanger<List<String>>();
		new ReadThread(exchanger).start();// 启动读数据线程
		new WriteThread(exchanger).start();// 启动写数据线程
	}
 
}
 
class ReadThread extends Thread {
	private Exchanger<List<String>> exchanger;
	List<String> bufferList ;
	
 
	public ReadThread(Exchanger<List<String>> exchanger) {
		this.exchanger = exchanger;
	}
 
	@Override
	public void run() {
		System.out.println("ReadThread start");
		
		try {
			bufferList = exchanger.exchange(bufferList);
			for (String str : bufferList) {
				System.out.println(str);
			}
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("ReadThread end");
	}
}
 
class WriteThread extends Thread {
	private Exchanger<List<String>> exchanger;
	List<String> bufferList = new LinkedList<String>();
	
	public static final Integer BUFFER_SIZE = 10;
 
	public WriteThread(Exchanger<List<String>> exchanger) {
		this.exchanger = exchanger;
	}
 
	@Override
	public void run() {
		try {
			System.out.println("WriteThread start");
			for (int i = 0; i < BUFFER_SIZE; i++) {
				bufferList.add(String.valueOf('A' + i)); // 模拟读数据
			}
			System.out.println("WriteTread 准备好数据,睡眠5秒钟");
			Thread.sleep(5000);
			bufferList = exchanger.exchange(bufferList); // 从Exchanger获得缓存数据
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		 
		System.out.println("WriteTread end");
 
	}
}




运行结果:
ReadThread start
WriteThread start
WriteTread 准备好数据,睡眠5秒钟
65
66
67
68
69
70
71
72
73
74
ReadThread end
WriteTread end

你可能感兴趣的:(Exchanger)