public class ThreadTest implements Runnable {
private int count = 20;
public void run() {
while (true) {
synchronized (this) {
if (count > 0) {
count--;
System.out.println(Thread.currentThread().getName() + "卖出一张票,剩余" + count + "张票");
}else {
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ThreadTest threadTest = new ThreadTest();
Thread t1 = new Thread(threadTest,"售票员1");
Thread t2 = new Thread(threadTest,"售票员2");
Thread t3 = new Thread(threadTest,"售票员3");
Thread t4 = new Thread(threadTest,"售票员4");
Thread t5 = new Thread(threadTest,"售票员5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
多线程卖票
最新推荐文章于 2022-12-06 19:36:48 发布