- class Ticket implements Runnable//extends Thread
- {
- private int tick = 300;
- Object obj = new Object();
- public void run()
- {
- while (true)
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- try
- {
- Thread.sleep(5);
- System.out.println(Thread.currentThread().getName()+"...sale: "+tick--);
- }
- catch(Exception e)
- {
- }
- }
- }
- }
- }
- }
- class ThreadTest3
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();//这个不是线程
- Thread th1 = new Thread(t);
- Thread th2 = new Thread(t);
- Thread th3 = new Thread(t);
- Thread th4 = new Thread(t);
- th1.start();
- th2.start();
- th3.start();
- th4.start();
- }
- }
复制代码 以买票的例子来说,如果把while循环放在synchronized里面,那释放锁的动作要等while循环结束才会做。这样第一个线程开始了,就会直接把票都卖完才会释放锁。
|
|