wait(),notify(),notifyAll()不属于Thread类,而是属于Object基础类,也就是说每个对像都有wait(),notify(),notifyAll()
的功能.因为都个对像都有锁,锁是每个对像的基础,当然操作锁的方法也是最基础了.
wait,它可以让当前线程暂时放弃对象锁,而将它暂时让给其它需要对象锁的人。当前的线程之前必须拥有此对象锁。调用对像wait方法后,当前线程释放对像锁,进入等待状态.直到其他线程(也只能是其他线程)通过notify唤醒. 但唤醒后还不一定拥有该对象锁,必须等到其他线程释放对象锁(如调用wait方法)重新获得对象锁的所有权后才能继续执行.
wait方法与notify方法必须在同步块内执行,即synchronized(obj之内).
看一个很经典的例子:
- package ProductAndConsume;
- import java.util.List;
- public class Consume implements Runnable{
- private List container = null;
- private int count;
- public Consume(List lst){
- this.container = lst;
- }
- public void run() {
- while(true){
- synchronized (container) {
- if(container.size()== 0){
- try {
- container.wait();//放弃锁
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- container.remove(0);
- container.notify();
- System.out.println("我吃了"+(++count)+"个");
- }
- }
- }
- }
- package ProductAndConsume;
- import java.util.List;
- public class Product implements Runnable {
- private List container = null;
- private int count;
- public Product(List lst) {
- this.container = lst;
- }
- public void run() {
- while (true) {
- synchronized (container) {
- if (container.size() > MultiThread.MAX) {
- try {
- container.wait();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- container.add(new Object());
- container.notify();
- System.out.println("我生产了"+(++count)+"个");
- }
- }
- }
- }
- package ProductAndConsume;
- import java.util.ArrayList;
- import java.util.List;
- public class MultiThread {
- private List container = new ArrayList();
- public final static int MAX = 5;
- public static void main(String args[]){
- MultiThread m = new MultiThread();
- new Thread(new Consume(m.getContainer())).start();
- new Thread(new Product(m.getContainer())).start();
- new Thread(new Consume(m.getContainer())).start();
- new Thread(new Product(m.getContainer())).start();
- }
- public List getContainer() {
- return container;
- }
- public void setContainer(List container) {
- this.container = container;
- }