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

轻松拿到这20分
public   class   TrainTicketSell  
{
        public   static   int   ticket=100;
        public   static   void   main(String   args[])
        {
                new   Sell().start();
                new   Sell().start();
                new   Sell().start();
                new   Sell().start();
        }
}


class   Sell   extends   Thread
{
        public   static   String   str=new   String   ( " ");
        public   void   run()
        {
              synchronized(str)
              {
                          while(TrainTicketSell.ticket> 0)
                                  System.out.println(Thread.currentThread().getName()+ ": "+TrainTicketSell.ticket--);
              }
        }
}
//不知道为什么只有一个线程在运行呀

------解决方案--------------------
你写的代码有问题,你run方法中的代码的同步块,还有一个循环语句,也就是说第一个进程进入这个同步块,要把所有的票售出能才退出这个同步块。当别的进程访问这个块时,因为没有票了,也打印不出数据来了。

把run方法中的代码改成下面就可以了
while(true) {
synchronized(str)
{
if(TrainTicketSell.ticket> 0)
System.out.println(Thread.currentThread().getName()+ ": "+TrainTicketSell.ticket--);
else
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

这样四个进程都能打印相应的数据
------解决方案--------------------
上面代码错了
public class TrainTicketSell
{
public static int ticket=100;
public static void main(String args[])
{
new Sell().start();
new Sell().start();
new Sell().start();
new Sell().start();
}
}


class Sell extends Thread
{
public String str=new String ( " ");
public void run()
{
synchronized(str)
{
while(TrainTicketSell.ticket> 0) {
TrainTicketSell.ticket--;

System.out.println(Thread.currentThread().getName()+ ": "+TrainTicketSell.ticket);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}
}
}
这能打印出很多4个零
------解决方案--------------------
手太慢了~~~~ 看到楼主的主贴,发现只要把while从 同步中放到同步前就可以实现楼主的目的、、、、、、、看下去发现已经、、、、、、、、、、、、、、、、