zoukankan      html  css  js  c++  java
  • Java中同一线程中的对象hashcode一样

    在同一个线程中创建的是统一个对像,获取的hashcode值是一样的,直接上代码了,写的不好不要介意!

    public static void main(String[] args) {
    for (int i = 0; i < 2; i++) {
    new Thread(new Runnable() {

    @Override
    public void run() {
    UserService us = UserService.getInstance();
    System.out.println(Thread.currentThread().getName()+" "+us );
    A a = new A();
    B b = new B();
    a.print();
    b.print();
    }
    }).start();
    }
    }
    static class A{
    public void print() {
    UserService us = UserService.getInstance();
    System.out.println("从A中获取:"+Thread.currentThread().getName()+"..."+us);
    }
    }

    static class B{
    public void print() {
    UserService us = UserService.getInstance();
    System.out.println("从B中获取:"+Thread.currentThread().getName()+"..."+us);
    }
    }
    }

    打印:

    Thread-0 com.test.UserService@10b7ce35
    Thread-1 com.test.UserService@407e3dad
    从A中获取:Thread-1...com.test.UserService@407e3dad
    从A中获取:Thread-0...com.test.UserService@10b7ce35
    从B中获取:Thread-0...com.test.UserService@10b7ce35
    从B中获取:Thread-1...com.test.UserService@407e3dad

  • 相关阅读:
    JVM如何执行方法调用
    JVM如何实现反射
    JVM是如何处理异常的
    Java类加载
    windows-Kafka安装
    Google Eventbus简单使用
    队列c#版
    python 元类

    Spring Mvc 笔记二之异常和文件上传
  • 原文地址:https://www.cnblogs.com/zlazm/p/7896510.html
Copyright © 2011-2022 走看看