| 
 
| 怎么随着sleep时间的增大,所有的ticket都被Thread-0卖掉了?我的锁明明是加在while循环的里面的。复制代码package hcy.test.main;
class ThreadDemo implements Runnable//extends Thread
{
private static int ticket=50;
public static Object obj=new Object();
public void run(){
while(true){
synchronized(obj){
try {
Thread.sleep(500);//睡眠0.5秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(0<ticket) 
System.out.println(Thread.currentThread().getName()+" run``` "+ticket--);
}
}
}
}
public class Test {
public static void main(String[] args){
// TODO Auto-generated method stub
ThreadDemo td=new ThreadDemo();
Thread thread1=new Thread(td);
Thread thread2=new Thread(td);
Thread thread3=new Thread(td);
Thread thread4=new Thread(td);
thread1.start();//
thread2.start();
thread3.start();
thread4.start();
}
}
输出结果如下:
 Thread-0 run```  50
 Thread-0 run```  49
 Thread-0 run```  48
 ·
 ·中间全是Thread-0 run```XX
 ·
 Thread-0 run```  3
 Thread-0 run```  2
 Thread-0 run```  1
 求解析?
 
 | 
 |