public class TestThread implements Runnable {
   private int x = 100;   public void run() {
      try
      {   
        test();
      } catch (InterruptedException e) {
           e.printStackTrace();     
        } 
   }   public synchronized void test() throws InterruptedException {
      x -= 10;
      Thread.sleep(4000);
      
      System.out.println("x = " + x);    
   }   public static void main(String[] args) throws Exception{
      TestThread tt1 = new TestThread();
      TestThread tt2 = new TestThread();
      Thread t1 = new Thread(tt1);
     
      t1.start();
      Thread.sleep(2000);
      tt1.test(); //(*)
      tt2.test(); //(**)
   }
}(**)这一句注释掉的结果为: |  (*)句注释掉的结果:
x = 90 (约共等待4s)        |   x = 90  (约共等待4s)
x = 80 (约共等待8s)        |   x = 90 (约共等待6s)
右边的结果好理解,左边的有一点不理解:
1)TestThread是一个线程类,那么它的对象tt1 和 用tt1 构造出来的Thread对象t1是什么关系?
2)test()是同步方法,如果t1和tt1是两个无关的类对象,那么同步对于他们是没有影响的,就如同右边的结果一样,但是左边的结果应该是tt1.test()是在t1线程结束之后才开始运行的,为什么?

解决方案 »

  1.   

    很好理解 就是因为休息了两个4000毫秒 所以是八秒Thread.sleep(2000);这个时间与第一个Thread.sleep(4000);重叠在一起所以时间是两个4000
      

  2.   

    1)TestThread是一个线程类,那么它的对象tt1 和 用tt1 构造出来的Thread对象t1是什么关系?
    不对  TestThread不是线程类 只是实现了Runnable接口
    可以用来传给Thread 构建Thread 对象通俗点说:tt1 ,tt2 是t1得要执行得任务
      

  3.   

    非常感谢ls的指教. 但是 (*) 和 (**)句都是两个对象"同时"执行一个同步方法,为什么t1,tt1"同时"执行的时候,就只能"同步地"执行;而t1,tt2"同时"执行的时候,就可以"并发地"执行?
      

  4.   

    t1,tt1都是调用ti对象的test方法 而这个方法是有synchronized 修饰的 所以不能同时执行
    t1,tt2 是执行不同的对象的test方法 所以可以并行
    Thread t1 = new Thread(tt2);你这样改 就是另外一种情况
      

  5.   

    这是对象的实例和线程两个问题,使用 tt1.test(); //(*)时,其实跑的是一个实例的两个线程,他们共用一个X变量,而tt2.test(); //(**) 时,是TestThread 类的两个实例,使用的是各自的x变量,所以会产生上述的结果。