【问题标题】:use of wait() and notify() in syncrhonized methods在同步方法中使用 wait() 和 notify()
【发布时间】:2014-06-30 10:05:58
【问题描述】:

如果我写了以下类:

public class Thread1 extends thread{
  int num;
  OtherObject obj;
  boolean isFinished;
  public Thread1(int num, OtherObject obj){
    this.num = num;
    this.obj = obj;
    isFinished = false;
  }

  public void run(){
    this.startMethod();
  }

  public synchronize void startMethod(){
    obj.anotherMethod()
    if(isFinished !=true)
      wait();
    isFinished = true;
    notifyAll();
  }

public class main{
  public static void main (String[] args){
    OtherObject other = new OtherObject();
    Thread1 first = new Thread1(1, other);
    Thread1 second = new Thread1(2, other);
    first.start();
    second.start();

*这段代码没有逻辑意义,只是代表了synchronized、wait()、notify()的思想。

1) 同步方法何时同步运行。 “第一”和“第二”是不同的对象,那么它们会同步吗?或不? 还是因为他们有共享变量 - OtherObject obj 他们会被同步?

2) 当我写 wait() 时,让我们说线程“首先”对象将进入睡眠状态并在什么时候醒来?

仅当来自同一类的另一个对象执行了 notify() 时? 或者当程序中的任何对象调用 notify() 时? 如果我在“OtherObject”类中编写通知,它也会使“第一个”对象唤醒?

3)“startMethod”是同步的,因此,当我 start() 第一个和第二个线程时,它们会执行 run 方法并启动“startMethod”。

“startMethod”是否同步完成?可能是因为它转到内部的“另一个方法”(不是同步方法),还是因为它从“运行”开始,也不是同步的? 我不明白标记为已同步的方法何时会同步,在什么情况下会停止同步?

【问题讨论】:

  • 不要试图让“没有逻辑意义”的代码多线程。具有逻辑意义的代码已经够难了。在您的情况下,您的代码似乎应该等到isFinishedtrue 并且然后isFinished 设置为true。无论多线程如何,这都不起作用。关于synchronized,您是从错误的一端尝试。首先,您必须完全了解为什么需要 synchronizedThere’s good literature around

标签: java multithreading synchronization synchronized


【解决方案1】:

3) 该方法是同步的,但仅针对该对象实例,两个线程将运行它而不会相互阻塞,因为它们是 2 个独立的实例。

2) 如果一个线程使用等待(你必须先有一个锁),它会进入等待模式,只有当另一个线程使用 same 锁时才会重新启动使用通知/nofityAll。如果具有不同锁的线程调用通知,则该特定线程不会发生任何事情。

侧节点:notify 告诉单个线程继续,但它是随机选择的,所以很多人更喜欢使用 notifyAll。

1) 如果您希望能够在共享变量上同步,您希望使用这个:

var Object obj; //assign instance on constructor or something like that

void method(){
    synchronized(obj){
         //sync code for obj instance
    }
}

【讨论】:

  • 在“//同步 obj 实例的代码”中,直到这段代码完成,没有人可以接近那个对象?
  • 也当在“//同步 obj 实例的代码”中调用其他方法?
  • 好吧,如果有其他地方没有同步该对象,他们将能够访问它,但同步代码一次只能执行一个线程,而其他任何地方都有指向该对象的相同同步。是的,您可以在其中添加任何语句。
猜你喜欢
  • 1970-01-01
  • 2019-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
相关资源
最近更新 更多