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

关于Thread的执行代码块疑问
今天看张效祥的java培训教程关于Thread有点不明白
代码如下:
class   TestThread   implements   Runnable
{
        int   tickets   =   100;
        String   str   =   new   String( " ");
        public   void   run()
        {
                if   (str.equals( "method "))
                {
                        while(true)
                        {
                                sale();
                        }
                }
                else
                {
                        while(true)
                        {
                                synchronized(str)
                                {
                                          if   (tickets   >   0)
                                          {
                                                    System.out.println(Thread.currentThread().getName()   +   "while   : "   +   tickets--);
                                                    try{Thread.sleep(1);}catch(Exception   e){}
                                          }
                                }

                        }
                }

        }
       
        public   synchronized   void   sale()
        {
                  if   (tickets   >   0)
                  {
                          System.out.println(Thread.currentThread().getName()   +   "sale   :   "   +   tickets--);
                          try{Thread.sleep(1);}catch(Exception   e){}