读书人

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

发布时间: 2012-10-08 19:54:56 作者: rapoo

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

实体

//教材public class Book {private int id;public Book(int id) {this.id = id;}@Overridepublic 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();}}

?

读书人网 >软件架构设计

热点推荐