完成操作系统作业Java模拟多线程卖票
/**
* @Author: crush
* @Date: 2021-05-12 16:24
* version 1.0
*/
public class SellTicketTask implements Runnable {
/**
* 一百张票
*/
private int ticketCount = 100;
@Override
public void run() {
while (true) {
// 同步代码块 防止超买 这一段也是临界区
synchronized (this) {
if (ticketCount <= 0) {
break;
} else {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
ticketCount--;
System.out.println(
Thread.currentThread().getName() + ":还剩下--" + ticketCount + "张票");
}
}
}
}
}启动多线程测试:
/**
* @Author: crush
* @Date: 2021-05-12 16:30
* version 1.0
*/
public class SellTickTaskDemo {
public static void main(String[] args) {
SellTicketTask sellTicketTask = new SellTicketTask();
Thread t1 = new Thread(sellTicketTask);
Thread t2 = new Thread(sellTicketTask);
Thread t3 = new Thread(sellTicketTask);
t1.setName("售票窗口1:");
t2.setName("售票窗口2:");
t3.setName("售票窗口3:");
t1.start();
t2.start();
t3.start();
}
}操作系统真的不简单。