欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

线程+栈 简单实现 生产者消费者关系

程序员文章站 2022-04-17 18:33:32
...
//生产
package test_produce;

public class Produce implements Runnable{
	Stack_used su;
	
	public Produce(){}
	public Produce(Stack_used su){
		this.su = su;
	}
	
//这里以生产100次为例
	public void run(){
		for(int i = 0; i < 100; i++){
			su.pushOne(i);
		}
	}

}



//消费

package test_produce;

public class Consume implements Runnable{
	Stack_used su;
	
	public Consume(){}
	public Consume(Stack_used su){
		this.su = su;
	}
	
	public void run(){
		for(int i = 0; i < 100; i++){
			su.popOne();
		}
	}
} 


//栈实现
package test_produce;

import java.util.Stack;

public class Stack_used {
	public static final int SIZE = 5;//定义生产上限
	Stack<Integer> stack ;
	
	public Stack_used(){
		super();
	}
	public Stack_used(Stack<Integer> stack){
		this();
		this.stack = stack;
	}
	
	public void pushOne(int n){
		synchronized(this){
			if(stack.size() >= Stack_used.SIZE){
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
	
			System.out.println("Produce:"+stack.push(n));
			
			//小睡一会,使结果明显一点
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			notifyAll();
		}
	}

	public void popOne(){
		synchronized(this){
			if(stack.isEmpty()){
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			
			System.out.println("--Consume:"+stack.pop());
			
			//小睡一会,使结果明显一点
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			notifyAll();
		}
	}
}



//测试

package test_produce;

import java.util.Stack;

public class Test {
	public static void main(String[] args) {
		Stack_used su = new Stack_used(new Stack<Integer>());
		Produce produce = new Produce(su);
		Consume consume = new Consume(su);
		
		new Thread(produce).start();
		new Thread(consume).start();

	}

}
/*
//部分结果...
 
Produce:0
Produce:1
Produce:2
Produce:3
Produce:4
--Consume:4
Produce:5
--Consume:5
--Consume:3
--Consume:2
--Consume:1
--Consume:0
Produce:6
Produce:7
Produce:8
Produce:9
--Consume:9
--Consume:8
--Consume:7
Produce:10
Produce:11
Produce:12
Produce:13
--Consume:13
--Consume:12
--Consume:11
--Consume:10
Produce:14
Produce:15
Produce:16
Produce:17
--Consume:17
--Consume:16
--Consume:15
--Consume:14
--Consume:6
Produce:18
Produce:19
--Consume:19
--Consume:18
...
 */ 
 
相关标签: thread