In below i'm trying to send two threads in singleton Pattern to see how the two threads working without synchronizing.In theory two threads should make two separate objects.But here without Synchronizing,only one object is creating and details of two threads are assigning two that object.I can see it when i print the object.How is that happening.why aren't there two objects are creating?
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;
}
}
Aucun commentaire:
Enregistrer un commentaire