典型的なマルチスレッド:生産と消費


エンティティ
// 
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();
	}

}