在下面的代码中,我期望两个线程中只有一个进入halt()函数,然后暂停程序。但是似乎两个线程都进入了synchronized halt()函数。为什么会这样呢?

package practice;

class NewThread implements Runnable {
  String name; // name of thread
  Thread t;
  boolean suspendFlag;

  NewThread(String threadname) {
    name = threadname;
    t = new Thread(this, name);
    System.out.println("New thread: " + t);
    suspendFlag = false;
    t.start(); // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for(int i = 15; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(200);
        Runtime r = Runtime.getRuntime();
        halt();
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }

  synchronized void halt() throws InterruptedException
  {
      System.out.println(name + " entered synchronized halt");
      Runtime r = Runtime.getRuntime();
      Thread.sleep(1000);
      r.halt(9);
      System.out.println(name + " exiting synchronized halt"); // This should never execute
  }
}

class Practice{
  public static void main(String args[]) {
    NewThread ob1 = new NewThread("One");
    NewThread ob2 = new NewThread("Two");

    // wait for threads to finish
    try {
      System.out.println("Waiting for threads to finish.");
      ob1.t.join();
      ob2.t.join();
    } catch (InterruptedException e) {
      System.out.println("Main thread Interrupted");
    }

    System.out.println("Main thread exiting."); // This should never execute
  }
}

最佳答案

同步在每个对象上完成。如果您有2个对象,则可能有2个线程同时进入halt()方法。您可以将方法设为静态以实现所需的功能。通过将其设置为静态,锁将被放置在相应的Class对象(NewThreadOne.class)上,该对象对于NewThreadOne的实例数而言是唯一的。

关于java - 了解同步关键字的工作原理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12411659/

10-11 16:51