package com.ccl.thread;
public class ProducerCustomer {
/**
* @author changlun.cheng
* @param args
* @see Product/Producer/Customer/Store 生产者与消费者
*/
public static void main(String[] args) {
Store s = new Store();
for (int i = 0; i < 4; i++) {
Producer pi = new Producer(s, i);
Thread tp = new Thread(pi);
tp.start();
Customer c = new Customer(s);
Thread tc = new Thread(c);
tc.start();
}
}
}
生产者类:
package com.ccl.thread;
public class Producer implements Runnable {
public Store s;
public int rank;
public Producer(Store s, int rank) {
this.rank = rank;
this.s = s;
System.out.println("new a producer.");
}
@Override
public void run() {
for (int i = 1; i < 41; i++) {
make(i + rank * 40);
}
}
private void make(int id) {
Product p = new Product(id);
s.push(p);
try {
Double d = Math.random() * 500;
Thread.sleep(d.longValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
产品类:
package com.ccl.thread;
public class Product {
public int Id;
public Product(int id) {
Id = id;
System.out.println("new a product . this is id: " + Id);
}
}
消费者类:
package com.ccl.thread;
public class Customer implements Runnable {
public Store s;
public Customer(Store s) {
this.s = s;
System.out.println("come on a customer.");
}
@Override
public void run() {
for (int i = 0; i < 40; i++) {
eat();
}
}
private void eat() {
Product p = s.pop();
System.out.println("customer eat " + p.Id);
try {
Double d = Math.random() * 1000;
Thread.sleep(d.longValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
仓库类:
package com.ccl.thread;
public class Store {
private int index = 0;
public Store() {
}
private Product[] array = new Product[10];
public synchronized void push(Product p) {
while (index == array.length) {
try {
this.wait();
System.out.println("a producer wait.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
array[index] = p;
index++;
}
public synchronized Product pop() {
while (index == 0) {
try {
this.wait();
System.out.println("a customer wait.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notifyAll();
index--;
return array[index];
}
}