zoukankan      html  css  js  c++  java
  • 单例模式/ThreadLocal/线程内共享数据

    import java.util.Random;

    public class ThreadDemo3 {

    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();
    data1.getIntance().setName("fdf"+data);
    data1.getIntance().setAge(data);
    System.out.println(Thread.currentThread().getName() + " data:" + data);
    System.out.println(Thread.currentThread().getName() + " hashcode "+data1.getIntance().getClass().hashCode());
    new a().get();
    new b().get();
    }

    }).start();

    }

    }

    static class a {

    public void get() {
    int data=data1.getIntance().getAge();
    System.out.println(Thread.currentThread().getName() + " a data:" + data);
    }
    }

    static class b {
    public void get() {
    int data=data1.getIntance().getAge();
    System.out.println(Thread.currentThread().getName() + " b data:" + data);
    }

    }

    }

    class data1{

    private String name;
    private int age;
    private static ThreadLocal<data1> mapdata=new ThreadLocal<data1>();
    private data1(){}

    public static data1 getIntance(){
    data1 da=mapdata.get();
    if(da==null)
    {
    da=new data1();
    mapdata.set(da);
    }

    return da;
    }

    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    public int getAge() {
    return age;
    }
    public void setAge(int age) {
    this.age = age;
    }


    }

  • 相关阅读:
    手把手教你用Python模拟登录淘宝
    数据库链接方式ORM
    ubuntu命令
    django项目不能运行解决方法
    区别比较 match和search
    redis持久化RDB与AOF
    python基础数据类型
    python基础二
    Python中将一个对象倒序输出的4种方法
    python基础数据类型补充以及编码的进阶
  • 原文地址:https://www.cnblogs.com/yugeng/p/7857345.html
Copyright © 2011-2022 走看看