现在的位置: 首页 > 综合 > 正文

四个线程加一减一试题

2014年01月03日 ⁄ 综合 ⁄ 共 1492字 ⁄ 字号 评论关闭

有一静态整形变量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--;
   }
  }
 }
}

抱歉!评论已关闭.