本帖最后由 缘木求鱼 于 2012-10-14 14:36 编辑
//ThreadTicketSimulated.java
class ThreadTicket implements Runnable{
private int tickets=100;
public synchronized void run(){
int i=0;
while(true){
if(tickets>0){
try{
Thread.sleep(100);
}catch(InterruptedException e){}
System.out.println(Thread.currentThread().getName()+"["+(i++)+"]"+" 出售票"+tickets--);
}else
break;//如果票数不足1则中断程序
}
}
}
public class ThreadTicketSimulated{
public static void main(String[] args){
ThreadTicket t=new ThreadTicket();
//启动了四个线程,并实现了资源共享
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
为什么运行结果之有一个Thread0线程?
|