zoukankan      html  css  js  c++  java
  • Java并发编程核心方法与框架-exchanger的使用

    Exchanger可以使两个线程之间传输数据,比生产者/消费者模式使用wait/notify更加方便。

    Exchanger中的exchange()方法具有阻塞的特点,此方法被调用后等待其他线程来取数据,如果没有其他线程取得数据,则一直阻塞等待。

    public class ThreadA extends Thread {
    	private Exchanger<String> exchanger;
    	public ThreadA(Exchanger<String> exchanger) {
    		super();
    		this.exchanger = exchanger;
    	}
    	@Override
    	public void run() {
    		try {
    			System.out.println("A线程获得的值:" + exchanger.exchange("String from threadA"));
    			System.out.println("threadA end");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    public class ThreadB extends Thread {
    	private Exchanger<String> exchanger;
    	public ThreadB(Exchanger<String> exchanger) {
    		super();
    		this.exchanger = exchanger;
    	}
    	@Override
    	public void run() {
    		try {
    			System.out.println("B线程获得的值:" + exchanger.exchange("String from threadB"));
    			System.out.println("threadB end");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    }
    
    public class Main {
    	public static void main(String[] args) {
    		Exchanger<String> exchanger = new Exchanger<>();
    		ThreadA a = new ThreadA(exchanger);
    		a.setName("A");
    		ThreadB b = new ThreadB(exchanger);
    		b.setName("B");
    		a.start();
    		b.start();
    		System.out.println("main end");
    	}
    }
    

    运行程序,控制台打印结果如下:

    main end
    A线程获得的值:String from threadB
    threadA end
    B线程获得的值:String from threadA
    threadB end
    
  • 相关阅读:
    WPF 打开文件 打开路径对话框
    WPF Button添加图片
    Delphi 正则表达式PerlRegEx
    解决Inet控件下载utf8网页乱码的问题
    Delphi程序结构
    VB 936(gb2312)URL编码与解码
    Chr 将一个有序数据转换为一个ANSI字符
    Delphi正则表达式使用方法(TPerlRegEx)
    Delphi类型转换
    Delphi 正则表达式TPerlRegEx 类的属性与方法
  • 原文地址:https://www.cnblogs.com/umgsai/p/5671634.html
Copyright © 2011-2022 走看看