- 线程间的数据交换:分同一个进程中的两个线程,不同进程的两个线程,下面聊下同一个进程中两个线程的数据交换。
- import java.util.concurrent.Exchanger;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- /**
- * 线程之间互换数据
- * @author Janrone
- * @website http://hujl.sinaapp.com
- */
- public class ExchangerDemo {
- /**
- * @param args
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- ExecutorService service=Executors.newCachedThreadPool();
- //线程之间交换数据
- final Exchanger<String> exchanger=new Exchanger<String>();
- service.execute(new Runnable() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- String data1="data1";
- System.out
- .println("线程"+Thread.currentThread().getName()+"正在把数据交换出去"+data1);
- try {
- Thread.sleep((long)(Math.random()*10000));
- String data2=exchanger.exchange(data1);
- System.out
- .println("线程"+Thread.currentThread().getName()+"换回来的数据"+data2);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- });
- service.execute(new Runnable() {
- @Override
- public void run() {
- // TODO Auto-generated method stub
- String data1="data2";
- System.out
- .println("线程"+Thread.currentThread().getName()+"正在把数据交换出去"+data1);
- try {
- Thread.sleep((long)(Math.random()*10000));
- String data2=exchanger.exchange(data1);
- System.out
- .println("线程"+Thread.currentThread().getName()+"换回来的数据"+data2);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- });
- service.shutdown();
- }
- }
线程间数据交换
最新推荐文章于 2020-05-12 13:53:15 发布