备注:来自小可08年的纸笔记,因为纸张快烂了,故此誊抄于此,以备不时只需,有的代码菜到几点,仅供娱乐。
package nie.test.util.thread;
import java.util.List;
import java.util.Vector;
/** 多线程之 生产者消费者 一种
* @author niewj
*/
public class TestMultiThread {
public static void main(String[] args) {
MyContainer container = new MyContainer();
Producer p = new Producer(container);
Consumer c = new Consumer(container);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
class MyContainer{
List<Object> lst = new Vector<Object>(); //承载容器
boolean flag = true; //标识位,默认为:无产品,可以生产了
/** 生产
* @param obj
* @throws InterruptedException
*/
synchronized public void push(Object obj) throws InterruptedException{
while(!flag){
wait();
}
lst.add(obj);
System.out.println("Produce One: "+obj);
flag = false;
notifyAll();
}
/** 消费
* @return
* @throws InterruptedException
*/
synchronized public Object pop() throws InterruptedException{
Object obj = null;
while(flag){
wait();
}
if(!lst.isEmpty()){
obj = lst.remove(0);
System.out.println("Consum One: "+obj);
flag = true;
notifyAll();
}else{
obj=null;
}
return obj;
}
}
class Consumer implements Runnable{
MyContainer con;
/** 初始化消费者的 容器 ,同生产者用同一个
* @param con
*/
public Consumer(MyContainer con) {
this.con = con;
}
@Override
public void run() {
while(true){
try {
Object obj = con.pop();
System.out.println(obj+" 被消费!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Producer implements Runnable{
MyContainer con;
/** 初始化生产者 用到的 容器,同消费者用同一个
* @param con
*/
public Producer(MyContainer con) {
this.con = con;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
Object obj = new Integer((int)(Math.random()*1000));; //产品
con.push(obj);
System.out.println(obj+" 被生产出来!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}