1.static实现线程范围内变量共享

package com.test.shareData;

import java.util.Random;

/**
 * 多线程范围内的数据共享
 * @author Administrator
 *
 */
public class ThreadScopeShareData {

    private static int data;
    public static void main(String[] args) {
        for(int i=0;i<2;i++){
            new Thread(new Runnable(){
                @Override
                public void run() {
                    data=new Random().nextInt();
                    System.out.println("currentThread:"+Thread.currentThread().getName()+" get data value is:"+data);
                    new A().get();
                    new B().get();
                    /**
                     * 输出:static 变量是内存中共享的,第二个线程的值会覆盖第一个线程的值
                     *  currentThread:Thread-0 get data value is:312589459
                        currentThread:Thread-1 get data value is:312589459
                        A currentThread:Thread-1 get data value is:312589459
                        A currentThread:Thread-0 get data value is:312589459
                        B currentThread:Thread-1 get data value is:312589459
                        B currentThread:Thread-0 get data value is:312589459
                     */
                }
            }).start();
        }
        
    }
    
    static class A{
        public void get(){
            System.out.println("A currentThread:"+Thread.currentThread().getName()+" get data value is:"+data);
        }
    }
    
    static class B{
        public void get(){
            System.out.println("B currentThread:"+Thread.currentThread().getName()+" get data value is:"+data);
        }
    }
}
View Code

相关文章:

  • 2022-01-01
  • 2022-01-01
  • 2022-01-01
  • 2021-08-17
  • 2021-08-27
  • 2021-11-15
  • 2021-09-30
  • 2022-01-12
猜你喜欢
  • 2022-12-23
  • 2022-01-01
  • 2022-01-01
  • 2021-10-25
  • 2021-12-16
  • 2022-12-23
相关资源
相似解决方案