package Test4;
/*
* 懒汉式单例模式
*/
public class Girl {
private static Girl girl = null;
private Girl() {
System.out.println("该对象只能自己调用");
}
public static Girl getGirl() {
if (girl == null) {
synchronized (Girl.class) {
if (girl == null) {
girl = new Girl();
}
}
}
return girl;
}
}
package Test4;
public class myRunnable implements Runnable {
@Override
public void run() {
String name = Thread.currentThread().getName();
Girl girl = Girl.getGirl();
for (int i = 0; i < 5; i++) {
System.out.println(name + " " + girl);
}
}
}
package Test4;
public class Test {
public static void main(String[] args) {
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
new Thread(new myRunnable()).start();
}
}
|
|