本帖最后由 邓利军 于 2012-9-25 20:50 编辑
今天默写售票程序,不加锁时多条线程都执行了,
但当我加上锁后,每次执行都只是其中一条执行,部分运行结果如下 :
Thread-0......ticket.....420
Thread-0......ticket.....419
Thread-0......ticket.....418
Thread-0......ticket.....417
Thread-0......ticket.....416
Thread-0......ticket.....415
Thread-0......ticket.....414
Thread-0......ticket.....413
Thread-0......ticket.....412
Thread-0......ticket.....411
Thread-0......ticket.....410
Thread-0......ticket.....409
Thread-0......ticket.....408
Thread-0......ticket.....407
Thread-0......ticket.....406
我的代码如下,为什么只有一条线程执行?脑子进死胡同了,百思不得其解,求解答............- class Ticket implements Runnable
- {
- private int num=500;
- private Object obj=new Object();
- public void run()
- {
-
- while(true)
- {
- synchronized(obj)
- {
- show();
- }
- }
- }
- public void show()
- {
- if(num>0)
- {
- try{Thread.sleep(100);}catch(InterruptedException e){}
- System.out.println(Thread.currentThread().getName()+"......ticket....."+num--);
- }
- }
- }
- class TicketDemo5
- {
- 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();
- }
- }
复制代码 |