50,503
社区成员
发帖
与我相关
我的任务
分享
package multiThread;
class BuyTicket implements Runnable{
private int ticket=10;
// private static int ticket=10;
@Override
public void run() {
// TODO Auto-generated method stub
{
while(ticket>0){
try{
synchronized (this){
System.out.println(Thread.currentThread().getName()+" get the NO."+ticket+"ticket");
ticket--;
}
Thread.sleep(1000);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
public BuyTicket(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BuyTicket a1=new BuyTicket();
new Thread(a1,"小王").start();
new Thread(a1,"小李").start();
new Thread(a1,"小刘").start();
}
}
synchronized (this) {
if(ticket > 0) {
System.out.println(Thread.currentThread().getName() + " get the NO." + ticket + "ticket");
ticket--;
}
}
即可保证ticket>0