了解同步关键字的工作原理



在下面的代码中,我希望两个线程中只有一个进入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
  }
}

synchronized不锁定方法,而是锁定对象。

您有一个方法,但有两个对象。每个线程都锁定自己的对象并调用halt()。

同步是在每个对象上完成的。如果您有两个对象,那么两个线程可能同时进入halt()方法。您可以将方法设置为静态,以实现您想要的内容。通过使其为静态,将锁定在对应的Class对象(NewThreadOne.class)上,该对象对于NewThreadOne的实例数量是唯一的。

您已将2 objects用于2 threads作为其monitor lock。。。。

因此,您的代码运行良好,每个线程访问其自己对象的锁以访问halt()方法。。。。

synchonized keyword中,您实现了对象的锁定,通过该锁定,线程可以访问该类中的synchronized methods or atomic statements。。。。。。

synchronized方法正在使用它进行锁定。在您的情况下,您有两个不同的对象,因为您正在构建两个线程实例,所以您没有锁定在同一个对象上。为了获得您期望的同步行为,您需要使halt方法static

不建议在java同步块中使用String对象作为锁,因为字符串是不可变的对象,文本字符串和中间字符串存储在字符串池中。因此,如果代码的任何其他部分或任何第三方库使用相同的String作为锁定,那么它们都将被锁定在同一对象上,尽管它们完全无关,这可能会导致意外行为和糟糕的性能。建议不要使用String对象,而是在synchronized块上使用Java中的new object()进行同步。

最新更新