A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© pig3156661 初级黑马   /  2014-8-2 20:52  /  839 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文


class Sale implements Runnable
{
        int tickets = 100;
        Object obj = new Object();
        public void run()
        {
                synchronized(obj)
                {
                        while(true)
                        {
                                try{Thread.sleep(10);}catch (Exception e){}
                                        if (tickets>0)
                                                System.out.println(Thread.currentThread().getName()+"…………"+tickets--);       
                               
                        }
                }
        }
}

class SaleTickets  
{
        public static void main(String[] args)
        {
                Sale s = new Sale();
                Thread t1 = new Thread(s);
                Thread t2 = new Thread(s);
                Thread t3 = new Thread(s);
                Thread t4 = new Thread(s);
                t1.start();
                t2.start();
                t3.start();
                t4.start();

        }
}
这个程序我用CMD输出后,放上同步代码块就只有0线程运行,而且CMD中就出现异常了,除非用CTRL+C终止,否则是没有办法输出完成的。求大神们帮忙解答!谢谢了!

4 个回复

倒序浏览
synchronized应该在while循环内,线程0进去之后一直有while循环,也补释放锁,别的线程也进不去啊,只能线程0一直执行
回复 使用道具 举报
class Sale implements Runnable {         int tickets = 100;         Object obj = new Object();         public void run()         {                 while(true){            synchronized(obj){                              try{Thread.sleep(10);}catch (Exception e){}                                         if (tickets>0)                       System.out.println(Thread.currentThread().getName()+"…………"+tickets--);                                                         }           }     } }  class SaleTickets   {         public static void main(String[] args)          {                 Sale s = new Sale();                 Thread t1 = new Thread(s);                 Thread t2 = new Thread(s);                 Thread t3 = new Thread(s);                 Thread t4 = new Thread(s);                 t1.start();                 t2.start();                 t3.start();                 t4.start();          } }      看下这个是否可以,
回复 使用道具 举报
zhouqun 发表于 2014-8-2 21:46
synchronized应该在while循环内,线程0进去之后一直有while循环,也补释放锁,别的线程也进不去啊,只能线 ...

谢谢大神指点!果然是!
回复 使用道具 举报
zhouqun 发表于 2014-8-2 21:46
synchronized应该在while循环内,线程0进去之后一直有while循环,也补释放锁,别的线程也进不去啊,只能线 ...

正解,while(true)放在外边就不一样了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马