有一静态整形变量X,初始值为0,用JAVA写四个线程,二个对其加1,二个对其减一,X等于0时不进行减操作,X等于5时结束程序。
上面代码有问题,run里边的X没有同步。
public class Test {
private static int res=0;
private Object lock = new Object();
public static void main(String[] args) {
Test t = new Test();
Runnable inc = t.new Inc();
Runnable dec = t.new Dec();
Thread t1 = new Thread(inc);
Thread t2 = new Thread(inc);
Thread t3 = new Thread(dec);
Thread t4 = new Thread(dec);
t1.start();
t2.start();
t3.start();
t4.start();
}
class Inc implements Runnable {
public void run() {
synchronized(lock) {
while (true) {
if(res == 5) return;
else res++;
}
}
class Dec implements Runnable {
public void run() {
synchronized(lock) {
while (true) {
if(res == 5) return;
else res--;
}
}
}
}