生产者消费者问题(java实现)

来源:互联网 发布:smt贴片机编程难吗 编辑:程序博客网 时间:2024/06/06 00:31
1、生产者、消费者模型(若容器容量为1)
生产者线程:
if(a ==1) {
wait()
}
a++;
notify;

消费者:
if (a == 0) {
wait();
}
a--;
notify;

2、下面是一个代码实现(简单的缓存容量只有1,即:若容器中有一个了,就不能再生产了):
(1)最基本的写法:
资源类:(资源类或者共享对象一般都写成一个单独的类,然后在线程中实现共享)
public class Sample {
private int a;
public synchronized void increase() {
if (a != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a++;
notify();
System.out.println(a);
}

public synchronized void decrease() {
if (a == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a--;
notify();
System.out.println(a);
}
}
线程类:
生产者线程类:
public class IncreaseThread extends Thread {
private Sample sample;
public IncreaseThread(Sample sample) {
this.sample = sample;
}

@Override
public void run() {
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sample.increase();
}
}
}
消费者线程类:
public class DecreaseThread extends Thread {
private Sample sample;
public DecreaseThread(Sample sample) {
this.sample = sample;
}

@Override
public void run() {
while (true) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
sample.decrease();
}
}
}
客户端测试类:
public class Test {
public static void main(String[] args) {
Sample sample = new Sample();
IncreaseThread increaseThread = new IncreaseThread(sample);
DecreaseThread decreaseThread = new DecreaseThread(sample);

increaseThread.start();
decreaseThread.start();
}
}
输出:
1
0
1
0
1
0

(2)这里存在一个问题,就是当有多个生产者和消费和消费者线程的时候,就会出现问题,输出的值并不一致是1 0 1 0。具体问题原因可以用代码具体分析一下。
解决方案:
资源类:
public class Sample {
private int a;
public synchronized void increase() {
while(a != 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a++;
notify();
System.out.println(a);
}

public synchronized void decrease() {
while(a == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a--;
notify();
System.out.println(a);
}
}
客户端类
public class Test {
public static void main(String[] args) {
Sample sample = new Sample();
IncreaseThread increaseThread = new IncreaseThread(sample);
DecreaseThread decreaseThread = new DecreaseThread(sample);

IncreaseThread increaseThread2 = new IncreaseThread(sample);
DecreaseThread decreaseThread2= new DecreaseThread(sample);

increaseThread.start();
decreaseThread.start();

increaseThread2.start();
decreaseThread2.start();
}
}
说明,一般都用while;(这里用if代码片段,纯粹是为了过度)

3、代码升级,容器容量是number=5;
和上面相比,仅需修改如下代码:
public class Sample {
public static int number = 5;
private int a;
public synchronized void increase() {
while (a >= 5){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a++;
notify();
System.out.println(a);
}

public synchronized void decrease() {
while (a <= 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
a--;
notify();
System.out.println(a);
}
}
0 0
原创粉丝点击