NO.5 线程范围内共享变量的概念与作用(二)

package thread;

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

public class ThreadScopeShareData {
    //private static int data = 1;
    private static HashMap<Thread, Integer> map = 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);
                map.put(Thread.currentThread(), data);
                new A().get();
                new B().get();
                
            }
        }).start();
        }
        
    }
    static class A{
        public void get() {
            System.out.println("A " + Thread.currentThread().getName() + "get data :" + map.get(Thread.currentThread()));
        }
    }
    static class B{
        public void get() {
            System.out.println("B " + Thread.currentThread().getName() + "get data :" + map.get(Thread.currentThread()));
        }
    }
}

在java中有现成的的类来处理线程间数据共享的 ThreadLocal

其应用场景有:

     1.订单处理包含一系列操作:减少库存,增加一条流水总账,修改总账,这几个操作要在同一个事务中完成,通常即同一个线程中进行处理,如果累加公司应收款的操作失败,则应该把前面的操作回滚。负责提交所有操作,这要求这些操作要使用相同的数据连接对象,而这些操作代码分别在不同的模块类中。

    2.银行转账包含一系列操作:把转出账户的余额减少,把转入账户的余额增加,这两个操作要在同一个事务中完成,他们必须使用相同的数据库连接对象,转入和转出操作的代码是在两个不同的模块类中。

  3.

 
原文地址:https://www.cnblogs.com/royi123/p/3122633.html