Java 线程技术模拟若干售票员售票

package SaleTickets;
public class SaleTickets implements Runnable{
private int tickets = 100;
public void run() {
for(int i = 1;i<=100;i++) {
if(tickets<=0) {
break;
}
System.out.println(Thread.currentThread().getName()+"售出第"+this.tickets--+"张票");

}
try {
Thread.sleep((int)(Math.random()*10));
}catch(InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+"窗口票已售完");
}
public static void main(String []args) {
SaleTickets r = new SaleTickets();
new Thread(r,"售票员A").start();
new Thread(r,"售票员B").start();
new Thread(r,"售票员C").start();
new Thread(r,"售票员D").start();
}

}

运行结果如下图所示:

Java 线程技术模拟若干售票员售票_第1张图片

你可能感兴趣的:(Java)