- class  TestThread
 
 - {
 
 -         public static void main(String[] args) 
 
 -         {
 
 -                 new Thread(new RunClass(0)).start();
 
 -                 new Thread(new RunClass(1)).start();
 
 -                 System.out.println("Hello World!");
 
 -         }
 
 - }
 
  
- class RunClass implements Runnable
 
 - {
 
 -         int flag=0;
 
 -         public RunClass(int flag)
 
 -         {
 
 -                 this.flag=flag;
 
 -         }
 
  
-         public void run()
 
 -         {
 
 -                 String str ="";
 
 -                 while(true)
 
 -                 {
 
 -                         if(flag==0)
 
 -                         {
 
 -                                 Test.fun1(str);
 
 -                         }
 
 -                         else
 
 -                         {
 
 -                                 Test.fun2(str);
 
 -                         }
 
 -                 }
 
 -         }
 
 - }
 
  
- class Test
 
 - {
 
 -         public static void fun1(String str)
 
 -         {
 
 -                 synchronized(str)
 
 -                 {
 
 -                         System.out.println("start Sleep");
 
 -                         try{Thread.sleep(1000);}catch(Exception e){}
 
 -                         System.out.println("end Sleep");
 
 -                         System.out.println("fun1:"+str);
 
  
-                 }
 
 -         }
 
  
-         public static void fun2(String str)
 
 -         {
 
 -                 synchronized(str)
 
 -                 {
 
 -                         System.out.println("fun2:"+str);
 
 -                 }
 
 -         }
 
 - }
 
 
  复制代码 
你看我上面这个代码的结果中 
start Sleep 
end Sleep 
之间是没有其他值的。也就是调用fun1的代码时,线程1 sleep了,线程2也是不执行的。因为使用的是同一个x参数 |