典型的多线程--生产和消费

实体

//教材
public class Book {
	private int id;

	public Book(int id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "教材" + id;
	}

}

 

 

仓库

public class ChangKu {
	//仓库大小
	private int index = 0;

	Book[] booklist = new Book[10];

	//同步入库
	public synchronized void put(Book book) {
		if (index >= 9) {
			try {
				System.out.println("仓库满了,等待取教材");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		booklist[index] = book;
		index++;
		this.notify();
	}

	//同步出库
	public synchronized Book get() {
		if (index == 0) {
			try {
				System.out.println("仓库空了,等待存教材");
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		Book book = booklist[--index];
		this.notify();
		return book;
	}
}

 

 

生产者

import java.util.Random;

public class Producer implements Runnable {
	ChangKu ck = null;

	public Producer(ChangKu ck) {
		this.ck = ck;
	}

	public void run() {
		while (true) {
			Book book = new Book((int) (Math.random() * 1000));
			ck.put(book);
			System.out.println("放入:" + book);
		}
	}
	
	

}

 

 

消费者

public class Consumer implements Runnable {
	ChangKu ck = null;

	public Consumer(ChangKu ck) {
		this.ck = ck;
	}

	public void run() {
		while (true) {
			Book book = ck.get();
			System.out.println("ȡ��取出" + book);
		}
	}

}

 

 

测试

public class TestPC {

	public static void main(String[] args) {
		ChangKu ck = new ChangKu();

		Producer pd = new Producer(ck);
		Consumer cs = new Consumer(ck);

		//生成线程
		Thread producer = new Thread(pd);
		//消费线程
		Thread consumer = new Thread(cs);
		
		producer.setName("put");
		consumer.setName("get");
		
		producer.start();
		consumer.start();
	}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值