4

我仍然是一个 java 新手,正在尝试学习线程。我的问题是它不会循环 5 次。它运行一次并退出。我正在使用 a.class 锁定类对象,这样两个线程都锁定在同一个对象监视器上。

class a implements Runnable {
  Thread thr;
  int count;
  String time;

  a(String s) {
    thr = new Thread(this, s);
    thr.start();
  }

  public void run() {
    count++;

    if (Thread.currentThread().getName().compareTo("one") == 0) {
      synchronized (a.class) {

        try {
          for (int i = 0; i < 5; i++) {
            System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);

            time = "Tick";
            System.out.println(time);
            notify();

            while (time == "Tock") {
              wait();
            }
          }
        } catch (Exception e) {
        }

      }
    } else if (Thread.currentThread().getName().compareTo("two") == 0) {
      synchronized (a.class) {
        try {
          for (int j = 0; j < 5; j++) {
            System.out.println("Now running thread " + Thread.currentThread().getName() + " with count " + count);

            time = "Tock";
            System.out.println(time);
              notify();

            while (time == "Tick") {
              wait();
            }
          }
        } catch (Exception e) {
        }
      }
    }
  }
}

public class b {
  public static void main(String args[]) {

    a obj1 = new a("one");
    a obj2 = new a("two");
  }
}
4

3 回答 3

3

给你,用原始代码:

class a implements Runnable {
    Thread thr;
    int count;
    static String time = "Tock";

    a(String s) {
        thr = new Thread(this, s);
        thr.start();
    }

    public void run() {
        count++;

        if (Thread.currentThread().getName().compareTo("one") == 0) {
            synchronized (a.class) {

                try {
                    for (int i = 0; i < 5; i++) {
                        while (time.equals("Tock")) {
                            a.class.wait();
                        }

                        System.out.println("Now running thread "
                                + Thread.currentThread().getName()
                                + " with count " + count);

                        time = "Tock";
                        System.out.println(time);
                        a.class.notify();                       
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else if (Thread.currentThread().getName().compareTo("two") == 0) {
            synchronized (a.class) {
                try {
                    for (int j = 0; j < 5; j++) {
                        while (time.equals("Tick")) {
                            a.class.wait();
                        }

                        System.out.println("Now running thread "
                                + Thread.currentThread().getName()
                                + " with count " + count);

                        time = "Tick";
                        System.out.println(time);
                        a.class.notify();                       
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class Test {
    public static void main(String args[]) {

        a obj1 = new a("one");
        a obj2 = new a("two");
    }
}

问题是你在隐式对象上调用waitand ,当锁被对象持有时,因此你必须调用on 。就是这样。notifythisa.classwait/notifya.class

我还做了一个小的重组,因为我假设您希望它们以交替顺序打印,对吗TickTock

于 2012-09-17T19:32:07.300 回答
2

在比较字符串(和一般的对象)时,您应该使用equals而不是==(通常为原语保留)while(time.equals("Tock")):. ==on strings 通常会导致false您希望它(并认为它应该)返回true,因此您的循环将在预期之前退出。

于 2012-09-11T23:24:53.467 回答
2

为什么你只循环一次的答案是你调用notify()了一个未锁定的对象,因此IllegalMonitorStateException被空的 catch 语句抛出并捕获。

这是一种方法。并不是说它是最好的。我试图让它靠近你的代码:

public class TickTock {
    static final int N = 4;

    Object lock = new Object();
    int token;

    class Worker extends Thread {
        int id;

        Worker(int id) {
            this.id = id;
        }

        @Override
        public void run() {
            try {
                synchronized (lock) {
                    for (int i = 0; i < 5; i++) {
                        while (id != token%N) lock.wait();

                        System.out.println(id + " " + i);

                        token++;
                        lock.notifyAll();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    void start() {
        for (int i = 0; i < N; i++) {
            new Worker(i).start();
        }
    }

    public static void main(String[] args) {
        new TickTock().start();
    }
}
于 2012-09-11T23:57:03.670 回答