为了使输出结果明显,我就每条线程上睡了50毫秒
package com.heima.jishu;
public class Test3 {
/**
* 定义一个买票程序,用实现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) {
e.printStackTrace();
}
System.out.println("当前窗口:Thread-1,剩余票数为: " + tickets
+ ",其中Thread-1中的1是第一个线程。");
tickets--;
} else if (Thread.currentThread().getName().equals("Thread-2")) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前窗口:Thread-2,剩余票数为: " + tickets
+ ",其中Thread-2中的2是第二个线程。");
tickets--;
} else if (Thread.currentThread().getName().equals("Thread-3")) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前窗口:Thread-3,剩余票数为: " + tickets
+ ",其中Thread-3中的3是第三个线程。");
tickets--;
} else {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前窗口:Thread-4,剩余票数为: " + tickets
+ ",其中Thread-4中的4是第四个线程。");
tickets--;
}
}
}
}
} |