• JAVA Exchanger


    //Exchanger工具类的使用案例 
    //本文给出一个简单的例子,实现两个线程之间交换数据,用Exchanger来做非常简单。
    
     
    
    import java.util.concurrent.Exchanger;
    import java.util.concurrent.atomic.AtomicReference;
    
    public class ThreadA implements Runnable {
    
      private final Exchanger<Integer> exchanger;
    
      private final AtomicReference<Integer> last = new AtomicReference<Integer>(
          5);
    
      public ThreadA(Exchanger<Integer> exchanger) {
        this.exchanger = exchanger;
      }
    
      public void run() {
        try {
          while (true) {
            last.set(exchanger.exchange(last.get()));
            System.out.println(" After calling exchange. Thread A has value: " + last.get());
            Thread.sleep(2000);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    
    }
    
    package my.concurrent.exchanger;
    
    import java.util.concurrent.Exchanger;
    import java.util.concurrent.atomic.AtomicReference;
    
    public class ThreadB implements Runnable {
    
      private Exchanger<Integer> exchanger;
    
      private final AtomicReference<Integer> last = new AtomicReference<Integer>(
          10);
    
      public ThreadB(Exchanger<Integer> exchanger) {
        this.exchanger = exchanger;
      }
    
      public void run() {
        try {
          while (true) {
            last.set(exchanger.exchange(last.get()));
            System.out.println(" After calling exchange. Thread B has value: " + last.get());
            Thread.sleep(2000);
          }
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    
    }
    
    package my.concurrent.exchanger;
    
    import java.util.concurrent.Exchanger;
    
    public class ExchangerTest {
    
      public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<Integer>();
        new Thread(new ThreadA(exchanger)).start();
        new Thread(new ThreadB(exchanger)).start();
      }
    
    }
  • 相关阅读:
    java JSONObject
    android 8.0 悬浮窗 最简demo
    使用adb 命令(atrace)抓起systrace的方法。
    使用python处理selenium中的获取元素属性
    使用adb/Linux获取网关ip
    Requests text乱码
    python-uiautomator2
    adb命令 判断锁屏
    缓存穿透、缓存击穿与缓存雪崩
    ReentrantLock重入锁详解
  • 原文地址:https://www.cnblogs.com/rojas/p/5367406.html
Copyright © 2020-2023  润新知