模拟消费者和生产者的多线程生产。
1,Resource.java定义了一个数组,生产者向里面存入数据,消费者从里面取出数据。
2,Input.java ,生产者线程
3,Output.java, 消费者线程
//创建资源类
Resource.java
package case98_ProducerConsumer;
//创建资源类
public class Resource {
// 创建存数数组
private int[] cell = new int[50];
// inPos表示存入时的数组下标,outPos表示取出时数组下标
private int inPos = 0, outPos = 0;
// cell[]数组里面当前的有效数数量
private int count = 0;
// 存数
public synchronized void put(int num) {
try {
while (count == cell.length)
this.wait();
cell[inPos] = num;
System.out.println(">put< 线程正在执行,并且放入数据 cell[" + inPos + "]" + "=" + cell[inPos] + "......");
inPos++;
if (inPos == cell.length)
inPos = 0;
count++;
this.notify();
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
// 取数
public synchronized int get() {
int data = 0;
try {
while (count == 0)
this.wait();
data = cell[outPos];
System.out.println(">get< 线程正在执行,并且取出数据 cell[" + outPos + "]" + "=" + cell[outPos]);
outPos++;
if (outPos == cell.length)
outPos = 0;
count--;
this.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
return data;
}
}
//创建存数线程,生产者
Input.java
package case98_ProducerConsumer;
//存数线程 ,生产者线程
public class Input implements Runnable {
private Resource s;
private int num = 0;
// 构造函数
public Input(Resource s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.put(num++);
if (num > 191)
num = 0;
}
}
}
//创建取数线程,消费者
Output.java
package case98_ProducerConsumer;
//取数线程, 消费者线程
public class Output implements Runnable {
private Resource s;
// 构造函数
public Output(Resource s) {
this.s = s;
}
@Override
public void run() {
while (true)
s.get(); // 循环取出元素
}
}
//创建主线程
ProducerConsumer.java
package case98_ProducerConsumer;
public class ProducerConsumer {
public static void main(String[] args) {
// 创建资源对象
Resource s = new Resource();
// 创建input对象
Input in = new Input(s);
// 创建output对象
Output out = new Output(s);
// 创建生产者线程
new Thread(in).start();
// 创建消费者线程
new Thread(out).start();
}
}
本文介绍了一个基于多线程实现的生产者消费者模式案例。通过定义Resource类管理共享资源,使用Input类作为生产者线程不断生成数据,Output类作为消费者线程消费这些数据。文章详细展示了如何利用synchronized关键字来同步线程间的操作。
7579

被折叠的 条评论
为什么被折叠?



