高手给布置的任务。
多线程最开始学Java的时候学的,今天写得很顺,自己都觉得挺吃惊。
还得查查资料,看这么写是不是最优的。
package com.weishubin.thread;
//生产者
public class Producer implements Runnable {
private ProductionStore store;
public Producer(ProductionStore store) {
this.store = store;
}
@Override
public void run() {
int i = (int) (100 * Math.random());
Production p = new Production(i);
try {
this.store.produce(p);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.weishubin.thread;
public class Consumer implements Runnable {
private ProductionStore store;
public Consumer(ProductionStore store) {
this.store = store;
}
@Override
public void run() {
try {
Production p = this.store.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
package com.weishubin.thread;
//产品
public class Production {
private int id;
public Production(int id) {
this.id = id;
}
public String toString() {
return "production:" + id;
}
}
package com.weishubin.thread;
import java.util.LinkedList;
public class ProductionStore {
private LinkedList productions = new LinkedList();
private int MAX_COUNT = 10;//最多存放10个产品
private int MIN_COUNT = 0;
public void produce(Production p) throws InterruptedException {
synchronized (productions) {
while (productions.size() == MAX_COUNT) {
System.out.println(Thread.currentThread() + " 生产等待:" + p);
productions.wait();
}
System.out.println(Thread.currentThread() + " 生产:" + p);
productions.add(p);
if (productions.size() == 1) {
productions.notifyAll();
}
}
}
public Production consume() throws InterruptedException {
synchronized (productions) {
int size = productions.size();
while (productions.size() == MIN_COUNT) {
System.out.println(Thread.currentThread() + "消费等待");
productions.wait();
}
Production p = productions.pop();
System.out.println(Thread.currentThread() + " 消费产品:" + p);
if (size == MAX_COUNT) {
productions.notifyAll();
}
return p;
}
}
}
package com.weishubin.thread;
public class App {
public static void main(String[] args) {
ProductionStore store = new ProductionStore();
for (int i = 0; i < 20; i++) {
Thread t = new Thread(new Producer(store));
t.start();
}
for (int i = 0; i < 20; i++) {
Thread t = new Thread(new Consumer(store));
t.start();
}
}
}