各位大神 小弟刚刚开始学习java不久,现在遇到一个线程难题 求解
package concurrency;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
class Tank2{
private int a = 0;
private int b = 0;
public synchronized int getA() {
return a;
}
public synchronized int getB() {
return b;
}
synchronized void operateFields(){
a++;
Thread.yield();
b++;
}
}
public class OperateThreadSyn implements Runnable{
Tank2 tank;
OperateThreadSyn(Tank2 tank){
this.tank =tank;
}
@Override
public void run(){
while((tank.getB() + tank.getA()) % 2 == 0){
System.out.println(Thread.currentThread().getName());
tank.operateFields();
}
System.out.println(Thread.currentThread().getName() + " :不是偶数,执行失败了!!");
}
public static void main(String[] args){
Tank2 tank = new Tank2();
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0 ; i < 3 ;i++){
exec.execute(new OperateThreadSyn(tank));
}
exec.shutdown();
}
}
//我已经synchronized所有涉及到a b 操作的方法了 为何还是出现了执行失败
------解决方案--------------------
该回复于2013-08-23 22:33:57被管理员删除