本文主要是介绍多线程和并发库应用十六-Exchanger,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
用于线程之间的数据交换,线程完成一定的数据后项目其他线程进行数据交换。第一个先拿出数据等到第二个线程执行完成后进行数据交换。
public class ExchangerTest {public static void main(String[] args) {ExecutorService service = Executors.newCachedThreadPool();final Exchanger exchanger = new Exchanger();service.execute(new Runnable(){public void run() {try { String data1 = "zxx";System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 +"换出去");Thread.sleep((long)(Math.random()*10000));String data2 = (String)exchanger.exchange(data1);System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);}catch(Exception e){}} });service.execute(new Runnable(){public void run() {try { String data1 = "lhm";System.out.println("线程" + Thread.currentThread().getName() + "正在把数据" + data1 +"换出去");Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1);System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为" + data2);}catch(Exception e){} } }); }
}
文章地址:http://www.haha174.top/article/details/259392
项目源码:https://github.com/haha174/thread-learning.git
这篇关于多线程和并发库应用十六-Exchanger的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!