本帖最后由 ぺsimon☆ 于 2013-5-16 00:06 编辑
- /*
- 有100张票,4个窗口在同时卖票,用多线程实现
- */
- class Ticket implements Runnable
- {
- //定义100张票
- private static int ticket=100;
- boolean flag=true;
-
- //覆盖run方法
- public void run()
- {
- synchronized(this)
- {
- while(flag==true && ticket>0)
- {
- try{Thread.sleep(10);}catch(Exception e){e.toString();}
- System.out.println(Thread.currentThread().getName()+"....."+ticket--);
- }
-
- }
- //调用show方法
- show();
- }
- public synchronized void show()
- {
- while(flag==false && ticket>0)
- {
- try{Thread.sleep(10);}catch(Exception e){e.toString();}
- System.out.println(Thread.currentThread().getName()+"------"+ticket--);
- }
- }
-
-
-
- }
- class TicketDemo
- {
- public static void main(String[] args)
- {
- Ticket t=new Ticket();
- Thread t1=new Thread(t);
- t1.start();
- //让主线程睡一会
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag=false;
- Thread t2=new Thread(t);
- t2.start();
- }
- }
复制代码 不知道为什么,从头到尾都是0线程在运行,1线程没有运行?谢谢
|