好久没动手写算法了,心血来潮就写一个。
有些不完美,请大家指教--Davis.Z
Java 生产者消费者编程
package com.davis.consumer;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
public class procon {
List<Thread> threads=new LinkedList<Thread>();
int MAXFOODACCOUNT = 10;
int FOODACCOUNT = 0;
private static int MAXTHREADNUM=6;
public static void main(String[] args) {
procon pc=new procon();
for(int i=0;i<MAXTHREADNUM;i++){
Producer p=pc.new Producer();
Consumer c=pc.new Consumer();
Thread pro=new Thread(p);
Thread con=new Thread(c);
pro.start();
con.start();
}
}
public synchronized void produce() throws InterruptedException
{
while(true)
{
this.notifyAll();
if(MAXFOODACCOUNT==FOODACCOUNT)
{
System.out.println("线程名:["+Thread.currentThread().getName()+"]仓库已满:"+FOODACCOUNT+"-----["+new Date()+"]");
}
else{
FOODACCOUNT++;
System.out.println("线程名:["+Thread.currentThread().getName()+"] 生产:"+FOODACCOUNT+"-----["+new Date()+"]");
Thread.sleep(100);
}
this.wait();
}
}
public synchronized void consume() throws InterruptedException
{
while(true){
this.notifyAll();
if(FOODACCOUNT<=0){
System.out.println("线程名:["+Thread.currentThread().getName()+"]库存量不足:"+FOODACCOUNT+"-----["+new Date()+"]");
}
else{
System.out.println("线程名:["+Thread.currentThread().getName()+"]消费:"+FOODACCOUNT+"-----["+new Date()+"]");
FOODACCOUNT--;
Thread.sleep(900);
}
this.wait();
}
}
class Producer implements Runnable{
public void run() {
// TODO Auto-generated method stub
try {
produce();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Consumer implements Runnable{
public void run() {
// TODO Auto-generated method stub
try {
consume();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
======
运行结果
===========================================================
线程名:[Thread-3]消费:2-----[Fri Mar 18 11:30:14 CST 2011]
线程名:[Thread-5]消费:1-----[Fri Mar 18 11:30:14 CST 2011]
线程名:[Thread-2] 生产:1-----[Fri Mar 18 11:30:15 CST 2011]
线程名:[Thread-7]消费:1-----[Fri Mar 18 11:30:15 CST 2011]
线程名:[Thread-4] 生产:1-----[Fri Mar 18 11:30:16 CST 2011]
线程名:[Thread-9]消费:1-----[Fri Mar 18 11:30:17 CST 2011]
线程名:[Thread-6] 生产:1-----[Fri Mar 18 11:30:17 CST 2011]
线程名:[Thread-8] 生产:2-----[Fri Mar 18 11:30:18 CST 2011]
线程名:[Thread-10] 生产:3-----[Fri Mar 18 11:30:18 CST 2011]
线程名:[Thread-11]消费:3-----[Fri Mar 18 11:30:18 CST 2011]
线程名:[Thread-0] 生产:3-----[Fri Mar 18 11:30:19 CST 2011]
线程名:[Thread-1]消费:3-----[Fri Mar 18 11:30:19 CST 2011]
线程名:[Thread-3]消费:2-----[Fri Mar 18 11:30:20 CST 2011]
线程名:[Thread-5]消费:1-----[Fri Mar 18 11:30:21 CST 2011]
线程名:[Thread-2] 生产:1-----[Fri Mar 18 11:30:21 CST 2011]
线程名:[Thread-7]消费:1-----[Fri Mar 18 11:30:22 CST 2011]
线程名:[Thread-4] 生产:1-----[Fri Mar 18 11:30:23 CST 2011]