1 开篇直言:
大厂规范要求一:尽量少用else…。
Google内部的代码标准强烈推荐使用return
1.1实例
与其这样
if(condition){
code;
}else{
return xxx;
}
不如这样
if(!condition){
return xxx;
}
code;
莫名其妙的错误
package demo11;
public class Box {
private int milk;
private volatile boolean flag = false;
public void put(int milk) {
synchronized (this) {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
this.milk = milk;
System.out.println("放入了" + this.milk + "牛奶");
flag = true;
notifyAll();
/**如果把后一段用else包起来,会出错的。细细品味两端代码的区别之处(提示:进程在哪跌倒在哪爬起)*/
/*if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else{
this.milk = milk;
System.out.println("放入" + this.milk + "牛奶");
flag = true;
notifyAll();
}
*/
}
}
public void get() {
synchronized (this) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
System.out.println("取出了" + this.milk + "牛奶");
flag = false;
notifyAll();
}
}
}