zoukankan      html  css  js  c++  java
  • java 多线程 day05 线程范围内的数据共享

    import java.util.HashMap;
    import java.util.Map;
    import java.util.Random;
    /**
    * Created by chengtao on 17/12/3.
    * 线程范围内的数据共享:即模块从不同的线程获取到的值是不一样的
    * 可以通过 hashMap<thread,data> 来将线程和对应的值通过map来区分
    */

    public class Thread0501_ThreadScopeShareData {

    private static int data = 0;
    public static void main(String[] args) {
    for(int i=0;i<2;i++){
    new Thread(new Runnable(){
    public void run() {
    data = new Random().nextInt();
    System.out.println(Thread.currentThread().getName()
    + " has put data :" + data);
    new A().get();
    new B().get();
    }
    }).start();
    }
    }

    static class A{
    public void get(){
    System.out.println("A from " + Thread.currentThread().getName() + " get data :" + data);
    }
    }

    static class B{
    public void get(){
    System.out.println("B from " + Thread.currentThread().getName() + " get data :" + data);
    }
    }
    }




    ----------------------------
    ----------------------------
    ----------------------------
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Random;

    /**
    * Created by chengtao on 17/12/3.
    * 线程间的数据共享
    */



    public class Thread0502_ThreadScopeShareData {

    private static int data = 0;
    private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
    public static void main(String[] args) {
    for(int i=0;i<2;i++){
    new Thread(new Runnable(){
    public void run() {
    int data = new Random().nextInt();
    System.out.println(Thread.currentThread().getName()
    + " has put data :" + data);
    threadData.put(Thread.currentThread(), data);
    new A().get();
    new B().get();
    }
    }).start();
    }
    }

    static class A{
    public void get(){
    int data = threadData.get(Thread.currentThread());
    System.out.println("A from " + Thread.currentThread().getName()
    + " get data :" + data);
    }
    }

    static class B{
    public void get(){
    int data = threadData.get(Thread.currentThread());
    System.out.println("B from " + Thread.currentThread().getName()
    + " get data :" + data);
    }
    }
    }
  • 相关阅读:
    1、线性DP 198. 打家劫舍
    1、线性DP 354. 俄罗斯套娃信封问题
    127. 单词接龙
    1. 线性DP 887. 鸡蛋掉落 (DP+二分)
    200. 岛屿数量
    1. 线性DP 152. 乘积最大子数组
    1. 线性DP 53. 最大子序和.
    1. 线性DP 120. 三角形最小路径和
    如何在RHEL 8上安装Python 3
    在Ubuntu 20.04 LTS Focal Fossa上安装Drupal
  • 原文地址:https://www.cnblogs.com/ctaixw/p/7967538.html
Copyright © 2011-2022 走看看