notify 和wait
要点:
1、 两者必须在synchronized内使用
2、wait使线程暂停执行,notify是线程得以继续执行
3、解决对同一数据对象,多线程访问的一致性
4、同步块代码执行时,其他线程序对同一对象的同步块代码被阻塞而不会执行,只有一个线程的同步块执行完毕,才会轮到其他线程的同步块执行
类Product
import java.util.List;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Product implements Runnable {
private List container = null;
private int count;
public Product(List lst) {
this.container = lst;
}
public void run() {
while (true) {
System.out.println("container.size()=" + container.size());
synchronized (container) {
if (container.size() > MultiThread.MAX) {
try {
System.out.println("Exceed the MAX limit.");
container.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
container.add(new Object());
container.notify(); //自动通知,快速生产
System.out.println("我生产了" + (++count) + "个");
}
// try {
// Thread.sleep(10);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//container.add(new Object());
//container.notify();
//System.out.println("我生产了" + (++count) + "个");
}
}
}
}
类Consume
import java.util.List;
/**
* @author Administrator
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
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 {
// System.out.println("container.size=0");
// container.wait();//放弃锁
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }else{
// container.remove(0);
// //container.notify();
// System.out.println("我吃了" + (++count) + "个");
// }
if(container.size() > 0){
container.remove(0);
// //container.notify();
System.out.println(Thread.currentThread().getId() + "我吃了" + (++count) + "个,还剩" + container.size());
}else{
container.notify();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//container.remove(0);
//container.notify();
//System.out.println("我吃了" + (++count) + "个");
}
}
}
}
类MultiThread
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;
}
}