码迷,mamicode.com
首页 > 其他好文 > 详细

Exchanger的使用

时间:2015-11-26 01:36:16      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:exchanger


线程之间交换数据,都到达才交换,游戏中道具、金币的交换

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerTest {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final Exchanger<String> exchanger = new Exchanger<String>();
        service.execute(new Runnable() {

            @Override
            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) {

                    e.printStackTrace();
                }
            }
        });

        service.execute(new Runnable() {

            @Override
            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) {

                    e.printStackTrace();
                }
            }
        });
    }
}


本文出自 “厚积薄发,磨刀不误砍柴工” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1716854

Exchanger的使用

标签:exchanger

原文地址:http://tianxingzhe.blog.51cto.com/3390077/1716854

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!