JAva:生産者と消費者のランダムな多数生産と消費
3263 ワード
import java.util.ArrayList;
import java.util.List;
/*
4 n , 40 , 100 ,
, 5 , 30 。
:
: XX 6
XX 4
, : 100 ! ..
, : ! ...*/
public class Bakery {//
Bread bread;//
List list = new ArrayList();// list
int holdermax = 100;// 100
int count = 0;
public List getList() {
return list;
}
/*
* public void setList(List list) { this.list = list; }
*
* /** list
*
* @throws InterruptedException
*/
public synchronized void push(Bread bread) throws InterruptedException {//
//
if (list.size() >= holdermax) {
wait();// , ,
System.out.println(" " + (list.size() + 1) + " , , ");
return;// return
}
list.add(bread);//
notify();// ,
}
/**
* list
*
* @throws InterruptedException
*/
public synchronized void down() throws InterruptedException {
//
if (list.size() <= 0) {// 1 , if
wait();
System.out.println(" " + list.size() + " , , ");
return;
}
list.remove(0);// list
notify();// ,
}
/**
* 0-100
*
* @return
*/
public int addRandon() {
int b = 0;
float a = (float) Math.random() * 100;// 0-1 , *100
if(a==0){
addRandon();// 0
}
return b = (int) a;//
}
}
//
public class Consumer implements Runnable {
// Bakery
Bakery bakery;
public Consumer(Bakery bakery) {
super();
this.bakery = bakery;
}
public void reduce() {
int b = 0;
while (true) {
try {
for (int i = 0; i < bakery.addRandon(); i++) {
if (i > 30) {
notify();
return;
} else {
bakery.down();
b = i;
}
}
System.out.println(Thread.currentThread().getName() + " " + b + " ");
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
reduce();
}
}
// ----------------------------------------------------
package 2;
public class Producer implements Runnable {
// Bakery
Bakery bakery;
public Producer(Bakery bakery) {
super();
this.bakery = bakery;
}
public void add() {
int b = 0;
while (true) {// while, , ,
Bread bread = new Bread();
try {
for (int i = 0; i < bakery.addRandon(); i++) {// ,
if (i > 40) {
notify();
return;
} else {
bakery.push(bread);// ,
b = i;
}
}
System.out.println(Thread.currentThread().getName() + " " + b + " ");
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
// TODO Auto-generated method stub
add();
}
}
--------------------------------------------
public class Bread {
}