在同一个线程中创建的是统一个对像,获取的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

相关文章:

  • 2021-12-25
  • 2021-08-08
  • 2021-07-19
  • 2021-07-14
  • 2021-07-18
  • 2021-06-24
猜你喜欢
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2021-05-23
  • 2022-01-04
  • 2022-12-23
相关资源
相似解决方案