了解多线程 [英] Understanding multi-threading

查看:102
本文介绍了了解多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对于并发运行的线程以及它们对对象的锁定有一个问题。据我所知,调用wait()方法的线程将进入等待列表,并允许来自阻塞列表的另一个线程接管锁定和对象(在同步代码中)。
如果现在对该对象具有锁定的此线程调用notify()方法,则它会唤醒调用wait()的线程并将其移动到阻止列表。

I just have a question in regards to threads that run concurrently and the lock they have on an object. From what I understand is that the thread that calls the wait() method will go on a waiting list and allows another thread from a blocked list to take over the lock on and object(within synchronized code). If this thread that now has the lock on the object calls the notify() method it wakes up the thread that called wait() and it is moved to the blocked list.

调用notify()方法的线程会发生什么。它是否仍然锁定对象或现在是否在等待名单上?

What happens to the thread that calls the notify() method. Does it still have a lock on the object or does it now go on a waiting list?

问候

推荐答案

只有一个线程可以保持对象的锁定。必须在线程持有对您调用这些对象的对象的锁时调用 wait() notify()方法方法;如果他们不这样做(例如,因为你没有在对象上同步),你将获得 IllegalMonitorStateException

Only one thread can hold the lock for an object. The wait() and notify() methods must be called while the thread holds the lock on the object you call these methods on; if they don't (for example, because you didn't synchronize on the object), you'll get an IllegalMonitorStateException.

当你调用 wait()时,线程放弃锁定并进入等待列表(停止执行)。当 wait()返回时,线程将再次获得锁定。但是,调用 notify()的线程仍然保持锁定,因此等待线程将不会在通知线程退出 synchronized之前恢复块或方法,以便释放对象的锁定。

When you call wait(), then the thread gives up the lock and goes on a waiting list (stops executing). When wait() returns, the thread will have obtained the lock again. However, the thread that calls notify() is still holding the lock, so the waiting thread will not resume before the notifying thread exits the synchronized block or method so that it releases the lock on the object.

通过调用 notify()线程没有放弃对象的锁定。

By calling notify() the thread is not giving up the lock on the object.

可能的事件序列是:


  • 线程1进入 synchronized 块,获取对象的锁定

  • 线程1调用 wait()对象,放弃锁定,停止执行

  • 线程2进入 synchronized 阻止,获取对象的锁

  • 线程2调用 notify()对象,但仍然持有锁

  • 线程1被唤醒并尝试获取锁,但它不能,因为线程2仍然拥有它(所以线程1必须等待锁)

  • 线程2退出 synchronized 阻止并释放锁

  • 线程1现在可以获取锁并从返回wait()

  • Thread 1 goes into a synchronized block, obtaining the lock for the object
  • Thread 1 calls wait() on the object, giving up the lock, stops executing
  • Thread 2 goes into a synchronized block, obtaining the lock for the object
  • Thread 2 calls notify() on the object, but still holds the lock
  • Thread 1 is awakened and tries to obtain the lock, but it can't because Thread 2 still has it (so Thread 1 has to wait for the lock)
  • Thread 2 exits the synchronized block and releases the lock
  • Thread 1 can now obtain the lock and returns from wait()

这篇关于了解多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆