public class BankTest {
public static void main(String[] args) {
Bank bank1 = Bank.getInstance();
}
}
class Bank{
private Bank(){}
private static Bank instance = null;
public static Bank getInstance(){//或者用同步方法,直接对这个方法添加synchronized属性
/* //方式一:效率较差
synchronized (Bank.class) {
if(instance == null){
instance = new Bank();
return instance;
}
return instance;
}*/
//方式二:效率更高
if(instance == null){
synchronized (Bank.class) {
if (instance == null) {
instance = new Bank();
}
}
}
return instance;
}
}
网友评论