在调用A中theMethod方法前判断该方法是否已被调用,用methodIsRun()
public class A{
private boolean flag = false;
public boolean methodIsRun(){ ruturn flag; }
public theMethod{
this.flag = true;
//方法主体
this.flag = flase;
}
}
public class A{
private boolean flag = false;
public boolean methodIsRun(){ ruturn flag; }
public theMethod{
this.flag = true;
//方法主体
this.flag = flase;
}
}
public class A{
private static boolean flag = false;
public boolean methodIsRun(){ ruturn flag; }
public theMethod{
if(flag = false)flag =true;
else return;
//方法主体
this.flag = flase;
}
}
private final static String flag = "0";
然后在方法中使用
synchronized(flag){
}
这种方法同步能不能做到该方法在该类的多个实例中同一时间内只有一个在运行?
public class A{
....
synchronized public void theMethod()//加关键字synchronized
{
.....
}
....
}
系统会自动的给你同步,也就是同一时间只有一个对象能使用这个方法;
public void run(){
(synchronized)theMethod();}
应用thread
private final static Object methodLock = new Object();........
public void theMethod() {
synchronized(methodLock ){ 。
}
}