- public class TicketDemo {
- public static void main(String args[])
- {
- Ticket t= new Ticket();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- t1.start();
- try{ Thread.sleep(10);}catch(Exception e){}
- t.flag= false;
- t2.start();
- }
- }
- class Ticket implements Runnable
- {
- boolean flag = true;
- private int ticket =100;
- //Object obj=new Object();
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(this)
- {
- if(ticket>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....code==="+ticket--);
- }
- }
- }
- }
- else
- while(true)
- show();
- }
- public synchronized void show(){
- if(ticket>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....show="+ticket--);
- }
- }
- }
复制代码
主方法t.flag已经赋值成false了。run方法里不就一直调用show了么。为什么还会执行if(flag) |