多线程同步代码块中的锁是怎么工作的...?代码中注释部分有啥作用?
- class Ticket implements Runnable
- {
- private int tick = 1000;
- Object obj = new Object();
- public void run()
- {
- while(true)
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- /*try
- {
- Thread.sleep(15);
- }
- 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();
- }
- }
复制代码 |
|