package wode.test;
class result{
Integer i;
public result(int i){
 this.i=i;
}
 public synchronized int method(boolean bol){
  
 if(bol==true){
i=new Integer(i.intValue()+1);
 }else{
i=new Integer(i.intValue()-1);
 }
return i.intValue();

}
}
class thread1 implements Runnable{
private result r;
public thread1(result r){
this.r=r;
}
public void run(){
   while(r.i.intValue()<20){
   int i=r.method(true);
   System.out.println(Thread.currentThread().getName()+" is running  i="+i);
   }
}
}
class thread2 implements Runnable{
private result r;
public thread2(result r){
this.r=r;
}
public void run(){
while(r.i.intValue()<20){
   int i=r.method(false);
   System.out.println(Thread.currentThread().getName()+" is running  i="+i);
   }
}
}
public class threadTest  {
  public static void main(String [] args){
  result r=new result(10);
  thread1 thd1=new thread1(r);
  thread1 thd2=new thread1(r);
  thread2 thd3=new thread2(r);
  thread2 thd4=new thread2(r);
  Thread td1=new Thread(thd1,"td1");
  Thread td2=new Thread(thd2,"td2");
  Thread td3=new Thread(thd3,"td3");
  Thread td4=new Thread(thd4,"td4");
  td1.start();
  td2.start();
  td3.start();
  td4.start();
  }
}
结果是:td1 is running  i=11
td1 is running  i=12
td1 is running  i=13
td1 is running  i=14
td1 is running  i=15
td1 is running  i=16
td1 is running  i=17
td1 is running  i=18
td1 is running  i=19
td1 is running  i=20
要求是写四个线程,对一个变量i同步操作,二个线程对变量i加1,二个线程对变量i减一,输出。 为啥答案只有thd1?我开始运行时还有其他三个,可后来运行就出不来了?哪位前辈帮忙看看,不胜感激!

解决方案 »

  1.   

    你这个问题牵扯到多线程编程中变量的可视性问题。这个问题往往容易被忽略。那么什么是变量的可视性呢?就拿你的程序中 result 类中的那个 i 来说,你只是同步了该变量的写方法(public synchronized int method(boolean bol)),但却没有同步它的读方法(其实你根本就没有读方法)。这样当你用 while(r.i.intValue() <20) 来读取该变量的值时,程序根本无法保证,那个读到的值是被及时更新了的(无可视性)。我把你的那个类修改了一下:public class Result {

    private Integer i; 

    public Result(int i){ 
    this.i=i; 


    public synchronized int method(boolean bol){    
    if(bol==true){
    i=new Integer(i.intValue()+1); 
    }else{ 
    i=new Integer(i.intValue()-1); 

    return i.intValue(); 
    }

    public synchronized Integer getI(){
    return this.i;
    }
    }
    这样当你用 while(r.getI().intValue() <20) 时,因为 getI 方法是同步的,所以变量 i 的值对于不同的线程来说是可视的。