java wait notify的用法
先看java doc如何说:
wait导致当前的线程等待,直到其他线程调用此对象的 notify() 要领或 notifyAll() 要领。当前的线程必须拥有此对象监视器。该线程揭晓对此监视器的一切权并等待,直到其他线程议决调用 notify 要领,或 notifyAll 要领告诉在此对象的监视器上等待的线程醒来。然后该线程将等到重新获得 对监视器的一切权后才能继续执行.
notify唤醒在此对象监视器上等待的单个线程。假如一切线程都在此对象上等待,则会挑选唤醒其中一个线程。直到当前的线程放弃此对象上的锁定,才能继续执行被唤醒的线程。此要领只应由作为此对象监视器的一切者的线程来调用.
"当前的线程必须拥有此对象监视器"与"此要领只应由作为此对象监视器的一切者的线程来调用"表明 wait要领与notify要领必须在同步块内执行,即synchronized(obj之内).
调用对像wait要领后,当火线程释放对像锁,进入等待形状 .直到其他线程(也只好是其他线程)议决 notify 要领,或 notifyAll.该线程重新获得 对像锁.
继续执行,记得线程必须重新获得 对像锁才能继续执行.由于 synchronized代码块内没有锁是寸步无法走的.看一个很经典的例子:
Code
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.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;
}
来源:oschina
链接:https://my.oschina.net/u/162189/blog/60834