生产者与消费者 代码实现 java

        首先,我利用忙测试写出了第一次版本的代码

 package How;
//自写代码 缺陷 无法完全实现pv操作线程处于忙测试状态
public class bin_1_1
{ public static void main(String[] args)
{
Producter producter; //生产者线程
Consumer consumer; //消费者线程
Buffer buffer;
buffer=new Buffer(10);
producter =new Producter(buffer);
consumer =new Consumer(buffer);
producter.start();
consumer.start();
} }
class Producter extends Thread
{
Buffer buffer;
public Producter(Buffer buffer)
{
this.buffer=buffer;
}
public void run()
{
while(true)
{ try
{
//模拟数据生产时间
Thread.sleep((int)Math.random()*5000+400);
IsEmpty(); //p(Empty)
//寻找空的缓存区 记录其标号为K
int k = 0;
for(int i=0; i<buffer.state_of_objs.length; i++)
{
if(buffer.state_of_objs[i]==0)
{
k=i;
break;
} }
write(k);
}
catch (InterruptedException e)
{ e.printStackTrace();
} }
}
synchronized public void IsEmpty() throws InterruptedException
{ while(true)
{
if(buffer.empty==0)
{
this.sleep(1);
}
else
{
buffer.empty--;
break;
}
}
}
public void write( int k ) //写入互斥,进制其他生产者访问
{
try
{
//模拟数据写入时间
Thread.sleep((int)Math.random()*1000+100);
//更改状态
System.out.println(Thread.currentThread().getName()+": 写"+k+"号缓存区");
buffer.state_of_objs[k]=1;
buffer.full++;
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Consumer extends Thread
{
Buffer buffer;
public Consumer(Buffer buffer)
{
this.buffer=buffer;
}
public void run()
{
while(true)
{
try
{
IsFull();
int k = 0;
for(int i=0; i<buffer.state_of_objs.length; i++)
{
if(buffer.state_of_objs[i]==1)
{
k=i;
break;
}
}
read(k);
//模拟消费时间
Thread.sleep((int)Math.random()*5000+300);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
synchronized public void IsFull() throws InterruptedException
{ while(true)
{
if(buffer.full==0)
{
this.sleep(1);
}
else
{
buffer.full--;
break;
}
}
}
public void read( int k)
{
try
{
//模拟读时间
Thread.sleep((int)Math.random()*3000+250);
System.out.println(Thread.currentThread().getName()+": 读"+k+"号缓存区");
//更改状态
buffer.state_of_objs[k]=0;
buffer.empty++;
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class Buffer //缓存区 临界资源记录区
{
int size; //缓存区大小
Object[] objs; //
int full=0;
int empty;
int []state_of_objs;
public Buffer(int size)
{
this.size=size;
this.empty=size;
objs =new Object[size];
state_of_objs=new int[size];
for(int i=0; i<size; i++)
{
state_of_objs[i]=0;
}
}
} 针对上述情况我,参考了一些其他人的代码
package How;
//参考代码 主要学习线程的各种锁!
public class bin_1_2 {
private static Integer count = 0;
private final Integer FULL = 10;
private static String LOCK = "LOCK"; class Producer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
synchronized (LOCK) {
while (count == FULL) {
try {
LOCK.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
count++;
System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count);
LOCK.notifyAll();
}
}
}
} class Consumer implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(3000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
synchronized (LOCK) {
while (count == 0) {
try {
LOCK.wait();
} catch (Exception e) {
}
}
count--;
System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count);
LOCK.notifyAll();
}
}
}
} public static void main(String[] args) throws Exception {
bin_1_2 bin_1_2 = new bin_1_2();
new Thread(bin_1_2.new Producer()).start();
new Thread(bin_1_2.new Consumer()).start();
new Thread(bin_1_2.new Producer()).start();
new Thread(bin_1_2.new Consumer()).start();
new Thread(bin_1_2.new Producer()).start();
new Thread(bin_1_2.new Consumer()).start();
new Thread(bin_1_2.new Producer()).start();
new Thread(bin_1_2.new Consumer()).start();
}
}
  这个代码为 多个消费者,生产者的问题,通过这个代码,我了解了synchronized使用方式。
package How;
//参考代码
import java.util.LinkedList; public class bin_1_3 {
private LinkedList<Object> storeHouse = new LinkedList<Object>();
private int MAX = 10; public bin_1_3()
{
} public void start() {
new Producer().start();
new Comsumer().start();
} class Producer extends Thread {
public void run() {
while (true) {
synchronized (storeHouse) {
try {
while (storeHouse.size() == MAX) {
System.out.println("storeHouse is full , please wait");
storeHouse.wait();
}
Object newOb = new Object();
if (storeHouse.add(newOb)) {
System.out.println("Producer put a Object to storeHouse");
Thread.sleep((long) (Math.random() * 3000));
storeHouse.notify();
}
} catch (InterruptedException ie) {
System.out.println("producer is interrupted!");
} }
}
}
} class Comsumer extends Thread {
public void run() {
while (true) {
synchronized (storeHouse) {
try {
while (storeHouse.size() == 0) {
System.out.println("storeHouse is empty , please wait");
storeHouse.wait();
}
storeHouse.removeLast();
System.out.println("Comsumer get a Object from storeHouse");
Thread.sleep((long) (Math.random() * 3000));
storeHouse.notify();
} catch (InterruptedException ie) {
System.out.println("Consumer is interrupted");
} }
} }
} public static void main(String[] args) throws Exception {
bin_1_3 pc = new bin_1_3();
pc.start();
}
}
    这个代码学习到了 LinkedList这个类库,从此我便可以快捷的方式实现栈,队列
最后我的改进代码如下:
package How;
class MyBuffer // 模拟缓冲区,这个为临界资源
{
String data; //模拟缓存区存放的数据
public MyBuffer(String data)
{
this.data=data;
}
} public class bin_1
{
public static void main(String[] args)
{
MyBuffer buffer=new MyBuffer("");
MyConsumer myConsumer=new MyConsumer(buffer);
MyProducter myProducter=new MyProducter(buffer);
myConsumer.start();
myProducter.start();
}
} class MyProducter extends Thread
{
MyBuffer buffer;
public MyProducter(MyBuffer buffer)
{
this.buffer=buffer;
}
//生产作业
public void ProducterJob()
{
//模拟生产时间
try
{
Thread.sleep((int )Math.random()*1000+400);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//进入互斥资源
synchronized (buffer)
{
if(buffer.data!="") //缓存区满着,阻塞
{
try
{
buffer.wait();
System.out.println("生产者等待");
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace(); }
}
buffer.data=""+System.currentTimeMillis();
System.out.println("生产者 :生产的数据为"+buffer.data);
buffer.notify(); //唤醒消费者
}
}
public void run()
{
while(true)
{
ProducterJob();
}
}
}
class MyConsumer extends Thread
{
MyBuffer buffer;
public MyConsumer(MyBuffer buffer)
{
this.buffer=buffer;
}
//消费作业
public void ConsumerJob()
{
//模拟消费时间
try
{
Thread.sleep((int )Math.random()*1000+600);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
//进入互斥资源
synchronized (buffer)
{
if(buffer.data=="") //缓存区为空,阻塞
{
try
{
buffer.wait();
System.out.println("消费者等待");
Thread.sleep(500);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println("消费者 :消费的数据为"+buffer.data); buffer.data="";
buffer.notify(); //唤醒生产者
}
}
public void run()
{
while(true)
{
ConsumerJob();
}
}
}

运行结果:

生产者与消费者        代码实现   java


上一篇:[Android] Sqlite 数据库操作 工具封装类


下一篇:手动搭建SpringMVC报错