使用Exchanger线程之间交换数据

发布时间:2023年12月22日
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;
	        }

	        @Override
	        public 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;
	        }

	        @Override
	        public 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());
	    }
	



}

文章来源:https://blog.csdn.net/ruiguang21/article/details/135153771
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。