本帖最后由 CHJ 于 2013-9-21 15:11 编辑
- class Ticket implements Runnable
- {
- private static int tick = 1000;
- //Object obj = new Object();
- boolean f = true;
- public void run()
- {
- if (f)
- {
- while(true)
- {
- synchronized(Ticket.class)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....sale : "+ tick--);
- }
- }
- }
- }
- else
- while(true)
- show();
- }
- public static synchronized void show()
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....show--- : "+ tick--);
- }
- }
- }
- class ThisLockDemo
- {
- 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){}//如果没有这行,t1、t2都会执行show(),那为什么加了这行,不是前10毫秒t1执行同步代码块,之后t1、t2都执行show()呢?
- t.f = false;
- t2.start();
- //t3.start();
- //t4.start();
- //Thread t3 = new Thread(t);
- //Thread t4 = new Thread(t);
- }
- }
复制代码 try{Thread.sleep(10);}catch(Exception e){}---------如果没有这行,t1、t2都会执行show(),那为什么加了这行,不是前10毫秒t1执行同步代码块,之后t1、t2都执行show()呢?
|