您的位置:首页 > 编程语言 > Java开发

CSDN JAVA版主老紫竹的一段模拟买火车票的多线程代码(转)

2008-07-17 09:40 543 查看
classtt{
publicstaticvoidmain(String[]args){
Runnablest=newSellThread();
newThread(st).start();
newThread(st).start();
newThread(st).start();
newThread(st).start();
}
}

classSellThreadimplementsRunnable{
inttickets=100;

Objectobj=newObject();

publicvoidrun(){
while(true)
{
synchronized(obj)

{
if(tickets>0){
System.out.println(Thread.currentThread().getName()+"selltickets"+tickets);
tickets--;
}else{
break;
}
}
try{
Thread.sleep(100);
}catch(Exceptione){
e.printStackTrace();
}
}
}
}
比较适合初学者理解同步,程序中的线程数到底有几个的问题,我一直对这个没有一个透彻的理解,实际上Threadxx=newThread();xx.start()只是启动了一个线程,不管run()方法中是不是有无限循环如while(true)。
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: