Java-经典消费者和生产者代码(面试题)

生产者代码

import java.util.Stack;

public class Consumer extends Thread{
	private Stack stack;
	
	Consumer( Stack stack){
		super();
		this.stack = stack;
	}
	
	@Override
	public void run() {
		synchronized (stack) {
			while(true){
				if(!stack.empty()){
					int pop = stack.pop();
					System.out.println("pop"+pop);
					stack.notify();
				}else{//等待				
					try {
						stack.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}		
	}
}

消费者代码

package syncreadandwrite;

import java.util.Stack;

public class Producer extends Thread{
	
	
	private Stack stack;
	
	Producer( Stack stack){
		super();
		this.stack = stack;
	}
	
	@Override
	public void run() {
		int i=0;
		synchronized (stack) {
			while(i<500){
				if(stack.empty()){//为空,生产数据.
					stack.push(i);
					System.out.println("push"+i);
					i++;
					stack.notify();
				}else{//不为空,等待数据被消费					
					try {
						stack.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}		
	}
}

启动类

package syncreadandwrite;

import java.util.Stack;

public class DemoClass {
	public static void main(String[] args) throws InterruptedException {
		Stack stack = new Stack();
		Producer p = new Producer(stack);
		Consumer c = new Consumer(stack);
		p.start();
		c.start();
	}
}

结果

push469
pop469
push470
pop470
push471
pop471
push472
pop472
push473
pop473
push474
pop474
push475
pop475
push476
pop476
push477
pop477
push478
pop478
push479
pop479
push480
pop480
push481
pop481
push482
pop482
push483
pop483
push484
pop484
push485
pop485
push486
pop486
push487
pop487
push488
pop488
push489
pop489
push490
pop490
push491
pop491
push492
pop492
push493
pop493
push494
pop494
push495
pop495
push496
pop496
push497
pop497
push498
pop498
push499
pop499

注意:notify()和wait()方法的配合使用,并且使用这两个方法的时候必须获取锁对象

你可能感兴趣的:(多线程)