当前位置:编程学习 > JAVA >>

线程范围内的共享变量

[java] 
package cn.itcast.demo; 
 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Random; 
 
public class ThreadScopeShareData { 
    /*
     * 线程范围内的共享变量
     * 作用:线程范围内的共享变量是指对同一个变量,几个线程同时对它进行写和读操作,
     * 而同一个线程读到的数据就是它自己写进去的数据。
     */ 
    private static int data = 0; 
    private static Map<Thread, Integer> map = new HashMap<Thread, Integer>(); 
    public static void main(String[] args) { 
        for (int i = 0; i < 2; i++) { 
            new Thread(new Runnable(){ 
                 
                public void run() { 
                    data = new Random().nextInt(); 
                    map.put(Thread.currentThread(), data); 
                    System.out.println(Thread.currentThread().getName() + ":MAIN--->" + map.get(Thread.currentThread())); 
                    new A().get(); 
                    new B().get(); 
                } 
            }).start(); 
        } 
        } 
     
        static class A{ 
            public void get() 
            { 
                System.out.println(Thread.currentThread().getName()+ "--->" + map.get(Thread.currentThread())); 
            } 
        } 
        static class B{ 
            public void get() 
            { 
                System.out.println(Thread.currentThread().getName()+ "--->" +map.get(Thread.currentThread())); 
            } 
        } 
     

 

补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,