请教大家,加上了synchronized之后,为啥原本的4个线程都执行,现在就只有一个线程在执行,无论把ticket改成多少都是?
- class Ticket implements Runnable
- {
- private int ticket = 100;
- Object obj = new Object();
- public void run()
- {
- while(true)
- {
- synchronized(obj)
- {
- if(ticket>0)
- {
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e){}
-
- System.out.println(Thread.currentThread().getName()+"......"+ticket--);
- }
- }
- }
- }
- }
- class ThreadTest2
- {
- 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();
- }
- }
复制代码 |
|