1. wait方法和notify方法

这两个方法,包括notifyAll方法,都是Object类中的方法。在Java API中,wait方法的定义如下:

public final void wait()
throws InterruptedException
Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).

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 notify method or the 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:

     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 notify method for a description of the ways in which a thread can become the owner of a monitor.

在 Java 中可以用 wait、notify 和 notifyAll 来实现线程间的通信。线程在运行的时候,如果发现某些条件没有被满足,可以调用wait方法暂停自己的执行,并且放弃已经获得的锁,然后进入等待状态。当该线程被其他线程唤醒并获得锁后,可以沿着之前暂停的地方继续向后执行,而不是再次从同步代码块开始的地方开始执行。但是需要注意的一点是,对线程等待的条件的判断要使用while而不是if来进行判断。这样在线程被唤醒后,会再次判断条件是否正真满足。

想象一下一个生产者,多个消费者的场景。一个消费者Consumer1了最后一个元素,并且唤醒了其他线程,如果被唤醒的正好是Consumer2,那么此时是没有元素可以消费的。如果用的是if判断,那么被唤醒后就不会再次进行条件的判断,而是直接向下执行导致运行错误。我们的代码如下:

notify方法会唤醒等待一个对象锁的线程,但是具体唤醒哪个是不确定的。

2. 实现生产者消费者

如下使用if来判断会导致程序出错

一定要使用while来进行判断线程的等待条件而不是使用if

 package thread.learn;

 import java.util.LinkedList;
import java.util.Queue;
import java.util.Random; /**
* Created by liujinhong on 2017/4/2.
* 生产者消费者问题是一个很经典的问题,值得好好研究一下
* java的wait和notify方法在使用时也是要非常注意的
*/
public class ProducerConsumer {
public static class Producer extends Thread {
Queue<Integer> queue;
int maxsize; Producer(Queue<Integer> queue, int maxsize, String name) {
this.queue = queue;
this.maxsize = maxsize;
this.setName(name);
}
@Override
public void run() {
while (true) {
synchronized (queue) {
try{
Thread.sleep(500);
} catch (Exception e) {} System.out.println(this.getName() + "获得队列的锁");
//条件的判断一定要使用while而不是if
if (queue.size() == maxsize) {
System.out.println("队列已满,生产者" + this.getName() + "等待");
try {
queue.wait();
} catch (Exception e) {}
}
int num = (int)(Math.random()*100);
queue.offer(num); System.out.println(this.getName() + "生产一个元素:" + num);
queue.notifyAll(); System.out.println(this.getName() + "退出一次生产过程!");
}
}
}
} public static class Consumer extends Thread {
Queue<Integer> queue;
int maxsize; Consumer(Queue<Integer> queue, int maxsize, String name) {
this.queue = queue;
this.maxsize = maxsize;
this.setName(name);
} @Override
public void run() {
while (true) {
synchronized (queue) {
try{
Thread.sleep(500);
} catch (Exception e) {} System.out.println(this.getName() + "获得队列的锁");
//条件的判断一定要使用while而不是if
if (queue.isEmpty()) {
System.out.println("队列为空,消费者" + this.getName() + "等待");
try{
queue.wait();
} catch (Exception e) {}
}
int num = queue.poll();
System.out.println(this.getName() + "消费一个元素:"+num);
queue.notifyAll(); System.out.println(this.getName() + "退出一次消费过程!");
}
}
}
} public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();
int maxsize = 2; Producer producer = new Producer(queue, maxsize, "Producer");
Consumer consumer1 = new Consumer(queue, maxsize,"Consumer1");
Consumer consumer2 = new Consumer(queue, maxsize,"Consumer2");
Consumer consumer3 = new Consumer(queue, maxsize,"Consumer3"); producer.start();
consumer1.start();
consumer2.start();
consumer3.start();
}
}

Java中wait()和notify()方法的使用的更多相关文章

  1. Java中wait和sleep方法的区别

    1.两者的区别 这两个方法来自不同的类分别是Thread和Object 最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法(锁代码块和方法锁). wait ...

  2. 转 Java中wait和sleep方法的区别

    1.两者的区别 这两个方法来自不同的类分别是Thread和Object 最主要是sleep方法没有释放锁,而wait方法释放了锁,使得其他线程可以使用同步控制块或者方法(锁代码块和方法锁). wait ...

  3. java中substring的使用方法

    java中substring的使用方法 str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str: str ...

  4. Java中Set的contains()方法

    Java中Set的contains()方法 -- hashCode与equals方法的约定及重写原则 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashCode() a ...

  5. [java,2017-05-16] java中清空StringBuffer的方法以及耗费时间比较

    java中清空StringBuffer的方法,我能想到的有4种: 1. buffer.setLength(0);  设置长度为0 2. buffer.delete(0, buffer.length() ...

  6. java中BorderLayout的使用方法

    相关设置: 使用BorderLayout布局上下左右中布局5个按键,单击中间的那个按键时就关闭窗口 代码: /**** *java中BorderLayout的使用方法 * 使用BorderLayout ...

  7. 【Java】Java中常用的String方法

    本文转载于:java中常用的String方法 1 length()字符串的长度 String a = "Hello Word!"; System.out.println(a.len ...

  8. Java中Set的contains()方法——hashCode与equals方法的约定及重写原则

    转自:http://blog.csdn.net/renfufei/article/details/14163329 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashC ...

  9. java中equals和hashCode方法随笔二

    前几天看了篇关于java中equals和hashCode方法的解析 1.Object类中的equals方法和hashCode方法. Object类中的equals和hashCode方法简单明了,所有的 ...

随机推荐

  1. Oracle性能优化之oracle中常见的执行计划及其简单解释

    一.访问表执行计划 1.table access full:全表扫描.它会访问表中的每一条记录(读取高水位线以内的每一个数据块). 2.table access by user rowid:输入源ro ...

  2. Redis的一些结构

  3. Oil Skimming---hdu4185(最大匹配)

    题目链接 题意:有一个地图.代表水#代表油每个单元格是10*10的,现有10*20的勺子可以提取出水上漂浮的油,问最多可以提取几勺的油: 每次提取的时候勺子放的位置都要是油,不然就被污染而没有价值了: ...

  4. 【Maven学习】Nexus私服代理其他第三方的Maven仓库

    一.背景 [Maven学习]Nexus OSS私服仓库的安装和配置 http://blog.csdn.net/ouyang_peng/article/details/78793038 [Maven学习 ...

  5. leetcode——Search for a Range 排序数组中寻找目标下标范围(AC)

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...

  6. django基础之Ajax、分页、cookie与session

    目录: Ajax之json Ajax简介 jquery实现的ajax js实现的ajax django分页器 COOKIE与SESSION 一.Ajax之json 1.什么是json? 定义: JSO ...

  7. Java基础知识Set、List、Map的区别

    就学习经验,浅谈Java中的Set,List,Map的区别,对JAVA的集合的理解是相对于数组: 数组是大小固定的,并且同一个数组只能存放类型一样的数据(基本类型/引用类型),JAVA集合可以存储和操 ...

  8. docker——三剑客之Docker Machine

    Docker Machine是Docker官方三剑客项目之一,负责使用Docker的第一步,在多种平台上快速安装Docker环境.它支持多种平台,让用户在很短时间内搭建一套Docker主机集群. Ma ...

  9. Debian更新软件源提示There is no public key available for the following key IDs的解决方法

    今天装了的debian7.0 但是更新软件源的时候出错 提示 W: There is no public key available for the following key IDs: 9D6D8F ...

  10. (13)如何使用Cocos2d-x 3.0制作基于tilemap的游戏:第一部分

    引言 程序截图: 本教程将会教大家如何使用Cocos2d-x来做一个基于tile地图的游戏,当然还有Tiled地图编辑器.(我们小时候玩的小霸王小学机里面的游戏,大部分都是基于tile地图的游戏,如坦 ...