生产消费模式及流程图

流程图
 

JAVA生产消费模式 - wj495175289 - 臭皮匠

 



package thread.stack;

import java.util.ArrayList;
import java.util.List;

/**
* 自制的栈(数据结构)

*/
public class Stack {

//堆栈数据结构实现的辅助变量
private List myList = new ArrayList();

/**
* 从集合中往外出字符
*/
public synchronized char pop() {
char temp;

// 当集合为空的时候直接等待
// 把资源直接交给另一个线程运行
while (myList.size() == 0) {
try {
System.out.println("集合中元素为空,等待生产者生产元素……");
wait();
} catch (Exception e) {
e.printStackTrace();
}

}

// 得到最后一个字符
temp = ((Character) (myList.get(myList.size() - 1))).charValue();

// 删除最后一个元素
myList.remove(myList.size() - 1);
// 当前线程的名字
String threadName = Thread.currentThread().getName();

System.out.println("消费者" + threadName + ":" + "消费了字符" + temp);

return temp;
}

/**
* 往集合里面添加字符
* @param c
*/
public synchronized void push(char c) {

// 添加元素
myList.add(c);

//当前线程的名字
String threadName = Thread.currentThread().getName();

System.out.println("生产者" + threadName + ":" + "生产了字符" + c);
// 唤醒其他线程
this.notify();
}

}

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package thread.stack;

/**
* 消费者类

*/
public class Consumer implements Runnable {

private Stack stack;

/**
* 生产者构造方法
*/
public Consumer(Stack stack) {
this.stack = stack;
}

/**
* 消费商品方法
*/
public void con() {
char c;

for (int i = 0; i < 200 i br>
// 集合(堆栈)中输出元素
c = stack.pop();

try {

// 等待30毫秒
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}

}

public void run() {
this.con();
}

}

、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package thread.stack;

/**
* 生产者类

*/
public class Producer implements Runnable {

private Stack stack;

/**
* 生产者构造方法
*/
public Producer(Stack stack) {
this.stack = stack;
}

/**
* 生产商品方法
*/
public void pro() {
char c;

for (int i = 0; i < 200 i br>
// 随机生成大写字母字符
c = (char) (Math.random() * 26 + 'A');

//往集合(堆栈)中添加元素
stack.push(c);

try {

//等待30毫秒
Thread.sleep(30);
} catch (Exception e) {
e.printStackTrace();
}
}

}

public void run() {
this.pro();
}

}
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
package thread.stack;

/**
* 客户端测试类

*/
public class Client {

public static void main(String[] args) {

//1.准备堆栈数据结构
Stack stack = new Stack();

//2.准备生产者线程
Producer producer1 = new Producer(stack);
Thread t1 = new Thread(producer1);

Producer producer2 = new Producer(stack);
Thread t2 = new Thread(producer2);

//3.准备消费者线程
Consumer consumer1 = new Consumer(stack);
Thread t3 = new Thread(consumer1);

Consumer consumer2 = new Consumer(stack);
Thread t4 = new Thread(consumer2);


t3.start();
t4.start();


t1.start();
t2.start();

}

}

猜你喜欢

转载自my.oschina.net/u/1013713/blog/1788013