本文主要是介绍使用Exchanger线程之间交换数据,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class ExchangeThread {static class Producer implements Runnable{//生产者、消费者交换的数据结构private List<String> buffer;//步生产者和消费者的交换对象private Exchanger<List<String>> exchanger;Producer(List<String> buffer,Exchanger<List<String>> exchanger){this.buffer = buffer;this.exchanger = exchanger;}@Overridepublic void run() {for(int i = 1 ; i < 5 ; i++){try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("生产者第" + i + "次提供");for(int j = 1 ; j <= 3 ; j++){System.out.println("生产者装入" + i + "--" + j);buffer.add("buffer:" + i + "--" + j);}System.out.println("生产者装满,等待与消费者交换...");try {exchanger.exchange(buffer);} catch (InterruptedException e) {e.printStackTrace();}}}}static class Consumer implements Runnable {private List<String> buffer;private final Exchanger<List<String>> exchanger;public Consumer(List<String> buffer, Exchanger<List<String>> exchanger) {this.buffer = buffer;this.exchanger = exchanger;}@Overridepublic void run() {for (int i = 1; i < 5; i++) {//调用exchange()与消费者进行数据交换try {buffer = exchanger.exchange(buffer);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("消费者第" + i + "次提取");for (int j = 1; j <= 3 ; j++) {System.out.println("消费者 : " + buffer.get(0));buffer.remove(0);}}}}public static void main(String[] args){List<String> buffer1 = new ArrayList<String>();List<String> buffer2 = new ArrayList<String>();Exchanger<List<String>> exchanger = new Exchanger<List<String>>();Thread producerThread = new Thread(new Producer(buffer1,exchanger));Thread consumerThread = new Thread(new Consumer(buffer2,exchanger));System.out.println("生产---->>>"+producerThread.getState());System.out.println("消费------>>>"+consumerThread.getState());producerThread.start();consumerThread.start();System.out.println("生产start---->>>"+producerThread.getState());System.out.println("消费start------>>>"+consumerThread.getState());}}
这篇关于使用Exchanger线程之间交换数据的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!