日期:2014-05-20  浏览次数:20723 次

java自定义的线程类对象和Thread类对象是什么关系?
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线程结束之后才开始运行的,为什么?

------解决方案--------------------
很好理解 就是因为休息了两个4000毫秒 所以是八秒

Thread.sleep(2000);这个时间与第一个Thread.sleep(4000);重叠在一起

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

------解决方案--------------------
up