class RunnableTicket implements Runnable{
private int tickets = 100;
private Object obj = new Object();
public void run(){
while(true){
synchronized(obj){
if(tickets>0){
try{
Thread.sleep(10);
}catch(Exception ex){}
System.out.println(Thread.currentThread().getName()+"出售第 "+tickets--);
}
}
}
}
}
public class ThreadDemo8 {
public static void main(String[] args) {
//创建Runnable即可实现类对象
RunnableTicket r = new RunnableTicket();
//创建Thread对象,传递接口实现类对象
Thread t0 = new Thread(r);
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
t0.start();
t1.start();
t2.start();
}
|
|