从Guarded Block来看Java中的wait和notify方法
2021-04-14 21:29
标签:指定 rdm 重载方法 Once 资源 活跃 文章 eth important Java线程的生命周期 本文探究一下Java最基础的机制之一:线程同步 多线程环境下,每个线程都可能去修改相同资源,如果线程没有被较好的管理,那就可能会出现并发问题。 多线程之间经常需要协同工作,最常见的方式是使用保护块(Guarded Blocks),它循环检查一个条件(通常初始值为true),直到条件发生变化才跳出循环继续执行。 但是使用Guarded Blocks的方法不停的检查循环条件实际上是一种资源浪费,更加高效的方法是调用Object.wait将当前线程挂起,直到有另一线程发起事件通知(尽管通知的事件不一定是当前线程等待的事件)。 我们今天要讨论的就是wait()和notify()方法: 补充:
* The current thread must own this object‘s monitor. The thread
* releases ownership of this monitor and waits until another thread
* notifies threads waiting on this object‘s monitor to wake up
* either through a call to the {@code notify} method or the
* {@code notifyAll} method. The thread then waits until it can
* re-obtain ownership of the monitor and resumes execution.
*
* As in the one argument version, interrupts and spurious wakeups are
* possible, and this method should always be used in a loop:
* 当一个线程调用wait方法时,它释放锁并挂起。然后另一个线程请求并获得这个锁并调用Object.notifyAll()通知所有等待该锁的线程(之后当前线程释放该锁),此时第一个线程收到通知获取到该锁,从wait()方法返回并继续执行。 wait()方法有三个重载方法: wait方法会使当前线程无限期等待,直到另一个线程调用了当前对象的notify()或notifyAll()方法。 这是另一个限期等待的重载方法,不同的是提供了更高精度的timeout。 notify()方法被用来唤醒在等待对象的内置锁的线程,有两种唤醒方式:
* The awakened thread will not be able to proceed until the current
* thread relinquishes the lock on this object. The awakened thread will
* compete in the usual manner with any other threads that might be
* actively competing to synchronize on this object; for example, the
* awakened thread enjoys no reliable privilege or disadvantage in being
* the next thread to lock this object.
*
* This method should only be called by a thread that is the owner
* of this object‘s monitor. A thread becomes the owner of the
* object‘s monitor in one of three ways:
*
* Only one thread at a time can own an object‘s monitor.
*/
它只会唤醒一个线程。但由于它并不指定哪一个线程被唤醒,所以一般大量相似任务的多线程环境中使用。因为对于这类任务,我们其实并不关心哪一个线程被唤醒。 对于该方法,当前线程必须拥有当前对象的内置锁或监视器锁(intrinsic lock aks monitor lock),根据Java文档,可通过以下三种方式的任意一种: 注意某一时间只有一个活跃线程能获取到对象的内置锁
* The awakened threads will not be able to proceed until the current
* thread relinquishes the lock on this object. The awakened threads
* will compete in the usual manner with any other threads that might
* be actively competing to synchronize on this object; for example,
* the awakened threads enjoy no reliable privilege or disadvantage in
* being the next thread to lock this object.
*
* This method should only be called by a thread that is the owner
* of this object‘s monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.
*/
该方法会唤醒所有在该对象上等待内置锁的线程。 在我们理解了上述叙述后,我们来看一个简单的生产者-消费者例子: 我们首先创建一个Drop类,它包含了生产者需要传送给消费者的数据,我们会使用wait()和notifyAll()方法来让两个线程之间共享数据: 我们来分解一下:· 因为线程唤醒后当前方法的循环条件不一定发生了改变。 假设o是用来调用wait的对象,当一个线程调用o.wait(),它必须要拥有o的内部锁(否则会抛出异常),获得d的内部锁的最简单方法是在一个synchronized方法里面调用wait()。 我们现在创建Producer和Consumer。 先看看Producer: 对Producer来说: 下面是Consumer的实现: 实现很简单,就是在for循环中调用drop.take()方法直到收到最后一个数据。 我们来运行一下程序: 程序输出如下: 可以看到,我们以正确的顺序收到了所有的消息数据并成功的在Producer和Consumer之间完成了数据共享。 本文讨论了Java的一些核心概念,更具体地说,我们聚焦在怎么使用wait()和notify()来解决同步问题,最后我们以一个简单例子说明了这些概念的使用。 值得一提的是这些都是低层次的API(wait、notify、notifyAll)。 测试代码 Guarded Blocks 从Guarded Block来看Java中的wait和notify方法 标签:指定 rdm 重载方法 Once 资源 活跃 文章 eth important 原文地址:https://www.cnblogs.com/mrcharleshu/p/13335024.html
预备知识
概览
我们先讨论一些并发相关的术语和方法论,接着会提供一个简单例子来处理并发问题,可以帮助我们更好的理解wait()和notify()方法。线程同步
public void guardedJoy() {
// Simple loop guard. Wastes processor time. Don‘t do this!
while(!joy) {}
System.out.println("Joy has been achieved!");
}
public synchronized void guardedJoy() {
// This guard only loops once for each special event,
// which may not be the event we‘re waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
下面这张图是wait()和notify()在线程的生命周期作用域的图解:
可以看到有很多种方式可以控制生命周期,本文我们只关注wait()和notify()方法。wait()方法
/**
* Causes the current thread to wait until another thread invokes the
* {@link java.lang.Object#notify()} method or the
* {@link java.lang.Object#notifyAll()} method for this object.
* In other words, this method behaves exactly as if it simply
* performs the call {@code wait(0)}.
*
* synchronized (obj) {
* while (<condition does not hold>)
* obj.wait();
* ... // Perform action appropriate to condition
* }
*
* This method should only be called by a thread that is the owner
* of this object‘s monitor. See the {@code notify} method for a
* description of the ways in which a thread can become the owner of
* a monitor.
*/
wait()
wait(long timeout)
wait(long timeout, int nanos)
notify() & notifyAll()
notify()
/**
* Wakes up a single thread that is waiting on this object‘s
* monitor. If any threads are waiting on this object, one of them
* is chosen to be awakened. The choice is arbitrary and occurs at
* the discretion of the implementation. A thread waits on an object‘s
* monitor by calling one of the {@code wait} methods.
*
*
*
notifyAll()
/**
* Wakes up all threads that are waiting on this object‘s monitor. A
* thread waits on an object‘s monitor by calling one of the
* {@code wait} methods.
*
被唤醒的线程正常执行下去直到完成任务。
但在允许唤醒的线程开始继续执行逻辑之前,我们通常会定义一个快速检查,以确定继续执行线程所需的条件,因为可能会出现这种被唤醒的线程没收到通知的情况(一个对象多个方法中都调用了wait(),但是notifyAll()可能只针对某个方法有意义)生产者-消费者同步问题
public class Drop {
// Message sent from producer to consumer.
private String message;
// True if consumer should wait for producer to send message,
// false if producer should wait for consumer to retrieve message.
private boolean empty = true;
public synchronized String take() {
// Wait until message is
// available.
while (empty) {
try {
wait();
} catch (InterruptedException e) {}
}
// Toggle status.
empty = true;
// Notify producer that
// status has changed.
notifyAll();
return message;
}
public synchronized void put(String message) {
// Wait until message has been retrieved.
while (!empty) {
try {
wait();
} catch (InterruptedException e) {}
}
// Toggle status.
empty = false;
// Store message.
this.message = message;
// Notify consumer that status
// has changed.
notifyAll();
}
}
为什么要把wait()方法放入while语句中?
为什么要同步put()和take()方法?
import java.util.Random;
public class Producer implements Runnable {
private Drop drop;
public Producer(Drop drop) {
this.drop = drop;
}
public void run() {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
};
Random random = new Random();
for (int i = 0;
i
import java.util.Random;
public class Consumer implements Runnable {
private Drop drop;
public Consumer(Drop drop) {
this.drop = drop;
}
public void run() {
Random random = new Random();
for (String message = drop.take();
! message.equals("DONE");
message = drop.take()) {
System.out.format("MESSAGE RECEIVED: %s%n", message);
try {
Thread.sleep(random.nextInt(5000));
} catch (InterruptedException e) {}
}
}
}
public class ProducerConsumerExample {
public static void main(String[] args) {
Drop drop = new Drop();
(new Thread(new Producer(drop))).start();
(new Thread(new Consumer(drop))).start();
}
}
MESSAGE RECEIVED: Mares eat oats
MESSAGE RECEIVED: Does eat oats
MESSAGE RECEIVED: Little lambs eat ivy
MESSAGE RECEIVED: A kid will eat ivy too
总结
有一些更高层次的API通常更简单且更好用,比如JDK中的Lock、Condition。关于这些可以看下我整理的一些文章参考
Oracle官方并发教程之Guarded Blocks
Oracle Java Tutorials "Intrinsic Locks and Synchronization"
Oracle Java Tutorials "Questions and Exercises: Concurrency"
上一篇:Python+unittest+request断言方法封装
下一篇:c++知识点4
文章标题:从Guarded Block来看Java中的wait和notify方法
文章链接:http://soscw.com/index.php/essay/75824.html