我的代码是:
public class Thread1{
public static void main(String[] args){
Basket ss=new Basket();
Producer pp=new Producer(ss);
Consumer cc=new Consumer(ss);
new Thread(pp).start();
new Thread(cc).start();
}
}class WoTo{
int id;
WoTo(int ff){
this.id=ff;
}
public String toString(){
return "wotot"+id;
}
}class Basket{
int index=0;
WoTo[] arrWt=new WoTo[6];
public synchronized void push(WoTo wt){
while(index==arrWt.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
arrWt[index]= wt;
index++;
}
public synchronized WoTo pop(){
while(index==0){
try {
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
index--;
return arrWt[index];
}
}class Producer implements Runnable {
Basket ss =null;
Producer( Basket tt){
this.ss=tt;
}
public void run(){
for(int i=0;i<20;i++){
WoTo wt=new WoTo(i);
ss.push(wt);
System.out.println("生产了:"+wt);
}
}
}class Consumer implements Runnable {
Basket jj=null;
Consumer (Basket nn){
this.jj=nn;
}
public void run(){
for(int j=0;j<20;j++){
WoTo wt=jj.pop();
System.out.println("消费了:"+wt);
}
}
}
我这个程序是生产一部分 然后消费一部分
执行显示后,竟然打印出来的有个别 消费的id竟然大于生产的id
也就是消费的比生产的多 请问一下 这是为什么? 急
public class Thread1{
public static void main(String[] args){
Basket ss=new Basket();
Producer pp=new Producer(ss);
Consumer cc=new Consumer(ss);
new Thread(pp).start();
new Thread(cc).start();
}
}class WoTo{
int id;
WoTo(int ff){
this.id=ff;
}
public String toString(){
return "wotot"+id;
}
}class Basket{
int index=0;
WoTo[] arrWt=new WoTo[6];
public synchronized void push(WoTo wt){
while(index==arrWt.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
arrWt[index]= wt;
index++;
}
public synchronized WoTo pop(){
while(index==0){
try {
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
index--;
return arrWt[index];
}
}class Producer implements Runnable {
Basket ss =null;
Producer( Basket tt){
this.ss=tt;
}
public void run(){
for(int i=0;i<20;i++){
WoTo wt=new WoTo(i);
ss.push(wt);
System.out.println("生产了:"+wt);
}
}
}class Consumer implements Runnable {
Basket jj=null;
Consumer (Basket nn){
this.jj=nn;
}
public void run(){
for(int j=0;j<20;j++){
WoTo wt=jj.pop();
System.out.println("消费了:"+wt);
}
}
}
我这个程序是生产一部分 然后消费一部分
执行显示后,竟然打印出来的有个别 消费的id竟然大于生产的id
也就是消费的比生产的多 请问一下 这是为什么? 急
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货