源代码:
package javasave.secondecode.packagecode;public class ThreadCode implements Runnable{
static int value=0;
static ThreadCode test=new ThreadCode();
static Thread runA=new Thread(test,"runA");
static Thread runB=new Thread(test,"runB");
  public void run(){
  if (Thread.currentThread().getName().equalsIgnoreCase("runA")) {
          synchronized(this) {
              try{
               wait();
              } catch(InterruptedException e){
  System.out.println("run error");
  }
          }
      }   while(value!=100){
  value++;
  System.out.println(Thread.currentThread().getName()+"\n"+value);
  if((value%10)==0){   synchronized(this) {
  try{
  wait();
  notify();
  } catch(InterruptedException e){
  System.out.println("run error");
  }
  }
  }
  }
  }
  public static void main(String args[]){
  runA.start();
  runB.start();
  }
}
为什么运行结果是
runB
1
runB
2
runB
3
runB
4
runB
5
runB
6
runB
7
runB
8
runB
9
runB
10

解决方案 »

  1.   

    一碰到runA线程就wait了,当然只有B的结果了
      

  2.   

    楼主大概想问为什么runA在synchronized块中等待时,runB执行吧
    wait()方法是让当前的线程等待,它有一个很重要的特点是它会释放
    它的锁,即解锁(具体就是你这里的this对象),所以runB讲获得执行
    的机会顺便说下sleep()方法,如果你在同步块中用的是sleep()而不是
    wait()结果会不同,原因很简单,sleep()方法并没有释放它的锁
    即使它休眠别的线程也不会获得执行次同步块的权利,除非
    sleep()结束,解锁
      

  3.   

    当然你不能讲那个同步块放在if中
    因为这样根本没什么意义,里面根本
    不需要同步(因为只有runA才能进去的)