/**
* 定义一个买票程序,用实现Runnable接口的方式,定义成员变量 tickets 值为100,创建4个线程同时买票,
* 每个线程输出语句格式:当前窗口:Thread-2,剩余票数为: 22,其中Thread-2中的2是第二个线程。
*/
public static void main(String[] args) {
BuyTicke bt1 = new BuyTicke("Thread-1");
BuyTicke bt2 = new BuyTicke("Thread-2");
BuyTicke bt3 = new BuyTicke("Thread-3");
BuyTicke bt4 = new BuyTicke("Thread-4");
new Thread(bt4).start();
new Thread(bt1).start();
new Thread(bt2).start();
new Thread(bt3).start();
}
}
class BuyTicke implements Runnable {
private static int tickets = 100;
public BuyTicke(String name) {
}
@Override
public void run() {
while (true) {
synchronized (BuyTicke.class) {
if (tickets == 0) {
break;
}
if (Thread.currentThread().getName().equals("Thread-1")) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {