zoukankan      html  css  js  c++  java
  • 17.Java5的Exchanger同步工具

     1 import java.util.concurrent.Exchanger;
     2 import java.util.concurrent.ExecutorService;
     3 import java.util.concurrent.Executors;
     4 
     5 /**
     6  * Java5的Exchanger同步工具
     7  * 用于实现两个人之间的数据交换,每个人在完成一定的事务后想与对方交换数据,
     8  * 第一个先拿出数据的人将一直等待第二个人那这数据到来时,才能彼此交换数据
     9  * @author LiTaiQing
    10  *
    11  */
    12 public class ExchangerTest {
    13     public static void main(String[] args) {
    14         ExecutorService service = Executors.newCachedThreadPool();
    15         final Exchanger<String> exchanger = new Exchanger<String>();
    16         service.execute(new Runnable() {
    17             public void run() {
    18                 try {
    19 
    20                     String data1 = "zxx";
    21                     System.out.println("线程" + Thread.currentThread().getName()
    22                             + "正在把数据" + data1 + "换出去");
    23                     Thread.sleep((long) (Math.random() * 10000));
    24                     String data2 = (String) exchanger.exchange(data1);
    25                     System.out.println("线程" + Thread.currentThread().getName()
    26                             + "换回的数据为" + data2);
    27                 } catch (Exception e) {
    28 
    29                 }
    30             }
    31         });
    32         service.execute(new Runnable() {
    33             public void run() {
    34                 try {
    35 
    36                     String data1 = "lhm";
    37                     System.out.println("线程" + Thread.currentThread().getName()
    38                             + "正在把数据" + data1 + "换出去");
    39                     Thread.sleep((long) (Math.random() * 10000));
    40                     String data2 = (String) exchanger.exchange(data1);
    41                     System.out.println("线程" + Thread.currentThread().getName()
    42                             + "换回的数据为" + data2);
    43                 } catch (Exception e) {
    44 
    45                 }
    46             }
    47         });
    48     }
    49 }
  • 相关阅读:
    不允许保存更改,阻止保存要求重新创建表的更改
    sql server导入excel等数据
    python爬虫框架(3)--Scrapy框架安装配置
    SQL server 2008安装教程
    python爬虫框架(2)--PySpider框架安装配置
    python爬虫框架(1)--框架概述
    python爬虫(8)--Xpath语法与lxml库
    FastReport Designer 应用
    BootStrap Table
    BootStrap Table
  • 原文地址:https://www.cnblogs.com/litaiqing/p/4651013.html
Copyright © 2011-2022 走看看