Java 多线程 ExecutorService Exchanger

Java 多线程 ExecutorService Exchanger

package thread.exchanger;

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

public class Test {

  /**
   * @author jzh 2011-12-27
   * @param args
   */
  public static void main(String[] args) {
    // 创建一个线程池(创建一个可根据需要创建新线程的线程池)
    // Executors 类提供了用于此包中所提供的执行程序服务的工厂方法
    ExecutorService pool = Executors.newCachedThreadPool();
    
    final Exchanger<String> exchanger = new Exchanger<String>();
    
    // 交换者
    pool.execute(new Runnable() {
      public void run() {
        try {
          String put = "iphone";
          System.out.println("jiang" + "正在把" + put + "换出去");
          Thread.sleep(100);
          String take = (String) exchanger.exchange(put);
          System.out.println("jiang"+ "换回" + take);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    
    // 交换者
    pool.execute(new Runnable() {
      public void run() {
        try {
          String put = "ipad";
          System.out.println("jzh" + "正在把" + put + "换出去");
          Thread.sleep(200);
          String take = (String) exchanger.exchange(put);
          System.out.println("jzh" + "换回" + take);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
    
    // 退出线程池
    pool.shutdown();
    
  }

}

 

发表回复

您的电子邮箱地址不会被公开。