元旦放假期间学代码,我都感动我自己啦。
试过了,OK的。
package demo.thread;
public class MyObject {
private static MyObject myObject ;
private MyObject() {
}
public static MyObject getInstance() {
try {
if (myObject != null){
} else {
Thread.sleep(3000L);
synchronized (MyObject.class) {
if (myObject == null){
myObject = new MyObject();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return myObject;
}
}
package demo.thread;
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(MyObject.getInstance().hashCode());
}
}
package demo.thread;
public class Run {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t1 = new MyThread();
t1.start();
MyThread t2 = new MyThread();
t2.start();
MyThread t3 = new MyThread();
t3.start();
}
}