/**帮我改一下这道程序,里面有少许的错误但是一直
*找不出来,请大虾帮我指点一下,为什么要那样做
*/
public class Li9_6 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
Store s= new Store();
Producer p2= new Producer(s,3);
Consumer c2= new Consumer(s,3);
p2.start();
c2.start();
}
}
class Producer extends Thread{
private Store store;
private int num;
// 构造方法
public Producer(Store s,int num) {
store=s;
this.num=num;
}
// 线程体
public void run() {
for(int i=0;i<10;i++) {
store.put(i); //放i到store对象
System.out.println("Producer#"+this.num+"put:"+i); //显示放数i
try {
sleep((int)(Math.random()*100)); //休眠0~100
}catch(InterruptedException e) {}
}
}
}//生产者Producer线程
class Consumer extends Thread{
private Store store;
private int num;
// 构造方法
public Consumer(Store s,int num) {
store =s;
this.num=num;
}
// 线程体
public void run() {
int value=0;
for(int i=0;i<10;i++) {
value=store.get();//从store对象取值
System.out.println("Consumer#"+this.num+"got:"+value);
}
}
}//Consumer线程class Store{
private int seq;
private boolean available=false;
public synchronized int get() {
while (available==false) {
try {
wait();
}
catch(InterruptedException e) {
}
}
available=false;
notify();
return seq;
}
public synchronized void put(int value) {
while(available==true) {
try {
wait();
}
catch(InterruptedException e) {
}
}
seq=value;
available=true;
notify();
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货