上代碼
package com.nice;
/**
* @author nice
*/
class Gril{
private volatile static Gril gril;
/**
*這裏的參數名BOY應該是boy,因爲之前寫的是final類型忘了改回去
*/
private static Boy BOY ;
static {
BOY = Boy.getBoy();
}
private Gril() {
System.out.println("女朋友只能有一個,是私有的");
}
/**
* 獲得女朋友
* @return Gril實體類
*/
public static Gril getGril() {
if (gril == null) {
synchronized (Gril.class) {
gril = new Gril();
}
}
else {
throw new RuntimeException("您的男朋友已出軌");
}
return gril;
}
/**
* 想男朋友了(遞歸引用,無限循環) 當然這裏用wait notify會更好
*/
public static void thinkBoy() {
System.out.println("我想我的男朋友了");
try {
Thread.sleep(520);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Boy boy = Boy.getBoy();
BOY.thinkGril();
}
}
class Boy{
private volatile static Boy boy;
private static Gril GRIL ;
static {
GRIL = Gril.getGril();
}
private Boy() {
System.out.println("男朋友只能有一個,是私有的");
}
/**
* 獲得男朋友
* @return Boy實體類
*/
public static Boy getBoy() {
if (boy == null) {
synchronized (Gril.class) {
boy = new Boy();
}
} else {
throw new RuntimeException("您的女朋友已出軌");
}
return boy;
}
public static void thinkGril() {
System.out.println("我想我的女朋友了");
try {
Thread.sleep(520);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Gril gril = Gril.getGril();
GRIL.thinkBoy();
}
}
public class LoveTest {
public static void main(String[] args) {
Boy boy = Boy.getBoy();
boy.thinkGril();
}
}
啊哈哈哈哈哈哈