黑马程序员技术交流社区

标题: 【黑马程序员】java练习:火车站售票 [打印本页]

作者: huburt    时间: 2016-5-22 22:09
标题: 【黑马程序员】java练习:火车站售票
  1. public class Exercise5Thread {
  2.         static int tacket = 100;
  3.         public static void main(String[] args) throws Exception {
  4.                
  5. //                Thread t1 = new Thread(){
  6. //                        @Override
  7. //                        public void run() {
  8. //                                this.setName("b");
  9. //                                System.out.println(Thread.currentThread().getName());
  10. //                        }
  11. //                };
  12. //                t1.start();
  13.                
  14. //                System.out.println(Thread.currentThread().getName());
  15.                
  16. //                Thread.sleep(1000);
  17.        
  18. //                t1.setDaemon(true);
  19.                 Sell s = new Sell();
  20.                 Thread t1 = new Thread(s);
  21.                 t1.setName("1号售票窗口");
  22.                 Thread t2 = new Thread(s);
  23.                 t2.setName("2号售票窗口");
  24.                 Thread t3 = new Thread(s);
  25.                 t3.setName("3号售票窗口");
  26.                 Thread t4 = new Thread(s);
  27.                 t4.setName("4号售票窗口");
  28.                
  29.                 t1.start();
  30.                 t2.start();
  31.                 t3.start();
  32.                 t4.start();
  33.                
  34.         }
  35. }

  36. class Sell implements Runnable{
  37.         int ticket = 100;
  38.         @Override
  39.         public void run() {
  40.                 while(true){
  41.                         synchronized(Sell.class){
  42.                                 if(ticket<=0){
  43.                                         break;
  44.                                 }
  45.                                 try {
  46.                                         Thread.sleep(10);
  47.                                 } catch (InterruptedException e) {
  48.                                         // TODO Auto-generated catch block
  49.                                         e.printStackTrace();
  50.                                 }
  51.                                 System.out.println(Thread.currentThread().getName()+"出售第"+(ticket--)+"票");
  52.                         }
  53.                 }
  54.         }
  55. }
复制代码

作者: 我有上将潘凤    时间: 2016-5-22 22:35
厉害,给你一个赞。。。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2