码迷,mamicode.com
首页 > 编程语言 > 详细

线程范围内共享变量的概念与作用

时间:2017-05-25 11:55:04      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:start   ash   from   print   ima   har   span   nbsp   logs   

package cn.itcast.heima2;

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

/**
 * 
 * @描述: 线程范围内共享变量的概念与作用 .
 * @作者: Wnj .
 * @创建时间: 2017年5月15日 .
 * @版本: 1.0 .
 */
public class 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() {
                @Override
                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);
        }
    }
}

 

线程范围内共享变量的概念与作用

标签:start   ash   from   print   ima   har   span   nbsp   logs   

原文地址:http://www.cnblogs.com/superGG/p/6902320.html

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