gpt4 book ai didi

java - 在单例模式中,当两个或多个线程同时执行时会发生什么?

转载 作者:行者123 更新时间:2023-11-30 12:08:40 24 4
gpt4 key购买 nike

<分区>

在下面,我试图在单例模式中发送两个线程,看看这两个线程在没有同步的情况下是如何工作的。理论上,两个线程应该创建两个单独的对象。但是这里没有同步,只有一个对象正在创建,两个对象的细节线程正在分配两个那个对象。当我打印对象时我可以看到它。这是怎么发生的。为什么没有两个对象正在创建?

public class Singleton_Pattern {

public static void main(String[] args) {
Test1 t1=new Test1();
t1.start();
Test2 t2=new Test2();
t2.start();
t1.m();
t2.m();
}
}

class Test1 extends Thread {

void m() {
System.out.println(A.getA());
A.getA().setValue("Cat");
System.out.println(A.getA().getValue());
}
}

class Test2 extends Thread {

void m() {
System.out.println(A.getA());
A.getA().setValue("Dog");
System.out.println(A.getA().getValue());
}
}

class A {

private static A a;
String name;

private A() {

}

public static A getA() {
if (a == null) {

a = new A();
}
return a;
}

public void setValue(String t) {
name = t;
}

public String getValue() {
return name;
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com