假设自习室有30个座位,50个学生需先预定才能在自习室上自习。当自习室座位全部被预定后,其余学生需要等待。当学生完成自习任务后,需取消预定的座位,以便其他等待的学生能够预定。程序框架如下,请补充完整这个java程序。public class Exp5 { public static void main(String[] args) throws Exception { BlockingQueue<Seat> seats = new ArrayBlockingQueue<>(30); Student[] students = new Student[50]; for (int i = 0; i < students.length; i++) { students[i] = new Student(seats, i + 1); } for (int i = 0; i < students.length; i++) { students[i].start(); } } } class Seat { } class Student extends Thread { BlockingQueue<Seat> seats; Seat seat; int studentNum; Student(BlockingQueue<Seat> seats, int studentNum) throws Exception { this.seats = seats; seat = new Seat(); this.studentNum = studentNum; } @Override public void run() { // fill here } void orderSeat() throws Exception { // fill here } void unorderSeat() throws Exception { // fill here } }
时间: 2024-02-14 10:11:16 浏览: 103
基于SpringBoot+thymeleaf的大学生自习室座位预定系统设计源码
public class Exp5 {
public static void main(String[] args) throws Exception {
BlockingQueue<Seat> seats = new ArrayBlockingQueue<>(30);
Student[] students = new Student[50];
for (int i = 0; i < students.length; i++) {
students[i] = new Student(seats, i + 1);
}
for (int i = 0; i < students.length; i++) {
students[i].start();
}
}
}
class Seat {
}
class Student extends Thread {
BlockingQueue<Seat> seats;
Seat seat;
int studentNum;
Student(BlockingQueue<Seat> seats, int studentNum) throws Exception {
this.seats = seats;
seat = new Seat();
this.studentNum = studentNum;
}
@Override
public void run() {
try {
orderSeat(); // 学生尝试预定座位
// 学生进行自习任务,这里暂时休眠 2 秒模拟自习任务
Thread.sleep(2000);
unorderSeat(); // 学生完成自习任务,取消座位预定
} catch (Exception e) {
e.printStackTrace();
}
}
void orderSeat() throws Exception {
seat = seats.take(); // 获取自习室座位,如果没有空位则阻塞
System.out.println("学生" + studentNum + "预定了座位" + seat);
}
void unorderSeat() throws Exception {
seats.put(seat); // 取消座位预定,将座位放回自习室座位队列中
System.out.println("学生" + studentNum + "取消了座位" + seat);
}
}
阅读全文