有一静态整形变量X,初始值为0,用JAVA写四个线程,二个对其加1,二个对其减一,X等于0时不进行减操作,X等于5时结束程序。
new Thread(add).start();
new Thread(add).start();
new Thread(sub).start();
new Thread(sub).start();
}
private synchronized void addOne() {
X++;
System.out.println(Thread.currentThread().getName()+" add one " + X);
}
private synchronized void subOne() {
X--;
System.out.println(Thread.currentThread().getName()+" sub one " + X);
}
class AddOne implements Runnable {
public void run(){
while (true) {
if (X == 5) {
System.out.println(Thread.currentThread().getName()+" add stop ");
return;
}
addOne();
try{
Thread.sleep(1000);
}catch(Exception e) {
}
}
}
}
class SubOne implements Runnable {
public void run() {
while (X != 0) {
if (X == 5) {
System.out.println(Thread.currentThread().getName()+" sub stop ");
return;
}
subOne();
try{
Thread.sleep(1000);
}catch(Exception e) {
}
}
}
}
}
上面代码有问题,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--;
}
}
}
}