为了那些还在像我一样找工作的人
package com.qimh.thread;
public class SyschorizedTest {
public static void main(String[] args) {
Stack stack = new Stack("stack");
Producter producter = new Producter(stack, "product");
Consumer consumer = new Consumer(stack, "consumer");
//启动线程
producter.start();
consumer.start();
}
}
//生产者
class Producter extends Thread{
private Stack stack ;
public Producter(Stack stack,String name){
super(name);
this.stack = stack;
}
@Override
public void run() {
String good;
for (int i = 0; i < 5; i++) {
synchronized (stack) {//这里的synchronized 作用是保证stack.getPoint();和stack.push(good); 是原子操作,因为这里在生产的时候直接把队列锁住了
good = "good" + stack.getPoint();
stack.push(good);
System.out.println(good + " 入栈");
}
}
}
}
//消费者
class Consumer extends Thread{
private Stack stack;
public Consumer(Stack stack,String name){
super(name);
this.stack = stack;
}
@Override
public void run() {
String good;
for (int i = 0; i < 5; i++) {
good = this.stack.pop();
System.out.println(good + " 出栈 ");
}
}
}
//堆栈
class Stack{
private String name;
private String[] buffer = new String[100];
Integer point = 1;
public Stack(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getPoint() {
return point;
}
//出栈
public synchronized String pop(){
String good = buffer[point];
if (good == null) {//栈里没有商品可以消费了
try {
wait();//让自己等待
good = buffer[point];
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
notifyAll();
}
buffer[point] = null;
point --;
return good;
}
//入栈
public synchronized void push(String goods){
if(point > 99){//如果栈满了,那么就不应该再向栈中添加数据了
try {
notifyAll();//唤醒消费者去消费
wait();//让自己等待
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{//向栈中添加
point++;
buffer[point] = goods;
notifyAll();//唤醒消费者去消费
}
}
}
执行结果:
good1 入栈
good2 入栈
good3 入栈
good4 入栈
good5 入栈
good5 出栈
good4 出栈
good3 出栈
good2 出栈
good1 出栈