输出由两个生产者随机生成字母存储在异步堆栈中,两个消费者从异步堆栈中获取字符:
首先,Java把内存分为两种:一种是栈内存,一种是堆内存
栈内存:在函数中定义的一些基本类型的变量和对象的引用变量,当超过变量的作用域之后,Java自动释放该变量内存
堆内存:存放new创建的对象和数组,由JVM的GC(Java虚拟机的自动垃圾回收器)管理。
我把异步理解成“步速不同”也就是线程的先后不同。
MyStack代码
package edu.ccut.pr;
import java.util.LinkedList;
public class MyStack<T> {
private LinkedList<T> list;
private int count;
public MyStack() {
list = new LinkedList<>();
count = 0;
}
public synchronized int getSize() {
return count;
}
// 压栈
public synchronized void push(T ele) {
while (count >= 200) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.addLast(ele);
count++;
this.notifyAll();
}
// 出栈
public synchronized T pull() {
while (count <= 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
T res = list.pollLast();
count--;
this.notifyAll();
return res;
}
// 查看最后的数据
public synchronized T peek() {
return list.peekLast();
}
}
生产者Producer代码
package edu.ccut.pr;
import java.util.Random;
public class Producer implements Runnable{
private MyStack<Character> stack;
public Producer(MyStack<Character> stack) {
this.stack = stack;
}
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
char c = generateChar();
stack.push(c);
System.out.println(Thread.currentThread().getName() + " : " + c);
}
}
private char generateChar() {
return (char) (new Random().nextInt(26) + 'A');//随机生成英文字母
}
}
消费者Consumer代码
package edu.ccut.pr;
public class Consumer implements Runnable{
private MyStack<Character> stack;
public Consumer(MyStack<Character> stack) {
this.stack = stack;
}
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println( Thread.currentThread().getName() + " : " + stack.pull());
}
}
}
main主函数
package edu.ccut.pr;
public class ProducerConsumer {
public static void main(String[] args) {
MyStack<Character> stack = new MyStack<>();
Runnable runnable = new Producer(stack);
Runnable runnable1 = new Consumer(stack);
for (int i = 0; i < 2; i++) {
Thread t1 = new Thread(runnable,"Producer1");
t1.start();
Thread t2 = new Thread(runnable,"Producer2");
t2.start();
try {
t2.join(15);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
Thread t3 = new Thread(runnable1,"Consumer1");
t3.start();
try {
t3.join(20);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
Thread t4 = new Thread(runnable1,"Consumer2");
t4.start();
}
}
}