为什么不能实现 每进行一下写入之后 才能进行一次读出操作!
下面代码始终没能找出问题来!!请大家看看
package threadz;public class threadcon{
public static void main(String args[]){
Q q = new Q();
new Thread(new put(q)).start();
new Thread(new get(q)).start(); }
}
class Q{
private String name,sex;
boolean bfull=false;
private int i=0; public synchronized void producer(){
if(bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
if(i==0){ this.name="zlz";
this.sex = "male";
this.i=1;
}
if(i==1){
this.name = "lili";
this.sex = "female";
this.i=0;
}
bfull=true; }
}
public synchronized void consumer(){
if(!bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
System.out.println(this.name+" and "+this.sex);
bfull=false;
notify();
}
}
}
class put implements Runnable{
private Q q=null;
put(Q q){
this.q=q;
}
public void run(){ while(true) q.producer();
}
}
class get implements Runnable{
private Q q=null;
get(Q q){
this.q=q;
}
public void run(){
while(true)
q.consumer();
}
}
下面代码始终没能找出问题来!!请大家看看
package threadz;public class threadcon{
public static void main(String args[]){
Q q = new Q();
new Thread(new put(q)).start();
new Thread(new get(q)).start(); }
}
class Q{
private String name,sex;
boolean bfull=false;
private int i=0; public synchronized void producer(){
if(bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
if(i==0){ this.name="zlz";
this.sex = "male";
this.i=1;
}
if(i==1){
this.name = "lili";
this.sex = "female";
this.i=0;
}
bfull=true; }
}
public synchronized void consumer(){
if(!bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
System.out.println(this.name+" and "+this.sex);
bfull=false;
notify();
}
}
}
class put implements Runnable{
private Q q=null;
put(Q q){
this.q=q;
}
public void run(){ while(true) q.producer();
}
}
class get implements Runnable{
private Q q=null;
get(Q q){
this.q=q;
}
public void run(){
while(true)
q.consumer();
}
}
修改方法,把producer()方法该为:
public synchronized void producer(){
if(bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
if(i==0){ this.name="zlz";
this.sex = "male";
this.i=1;
}
else if(i==1){
this.name = "lili";
this.sex = "female";
this.i=0;
}
bfull=true;
notify();
~~~~~
}
}
这两句话 可是
结果总是打印 LILI AND FEMALE
不知道问题在哪里 情大家帮忙看看
public synchronized void producer(){
if(bfull){
try{
wait();
}
catch(Exception e){
}
}
else{
if(i==0){ this.name="zlz";
this.sex = "male";
this.i=1;
}
else if(i==1){
~~~~~
this.name = "lili";
this.sex = "female";
this.i=0;
}
bfull=true;
notify();
~~~~~
}
}
看到了吗?不需要我解释为什么了吧,呵呵,以后写东西要细心.
我刚学JAVA撒