- //卖票小程序
- class Ticket implements Runnable//extends Thread
- {
- private int tick=100;//票的数量
- Object obj=new Object();
- public void run()
- {
- while(tick>0)
- {
- synchronized(obj)//同步代码块
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+" sale:"+tick--);
- }
- }
- }
- }
- class TicketDemo2
- {
- public static void main(String[] args)
- {
- Ticket t=new Ticket();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- Thread t3=new Thread(t);
- Thread t4=new Thread(t);
- t1.start();
- t2.start();
- t3.start();
- t4.start();
- }
- }
复制代码
运行结果:
......
......
Thread-0 sale:5
Thread-0 sale:4
Thread-0 sale:3
Thread-0 sale:2
Thread-0 sale:1
Thread-3 sale:0
Thread-2 sale:-1
Thread-1 sale:-2
我已经使用同步代码块了,为什么还会出现0,-1,-2的票呢,还请大家多多指教。 |
|