线程基础题
题目 1:模拟多人餐厅点餐
场景:在一家餐厅里,有多个顾客(线程)向服务员点餐,服务员(线程)依次处理每个顾客的订单,每个订单处理需要一定时间(模拟 sleep)。当所有顾客都完成点餐,服务员开始准备餐食。
要求:
- 创建 Customer 类实现 Runnable 接口,每个顾客线程在构造时传入自己的名字,线程任务是向服务员发出点餐请求。
- 创建 Waiter 类实现 Runnable 接口,服务员线程接收顾客的点餐请求,按顺序处理,并在处理完所有顾客订单后,打印开始准备餐食的信息。
- 在 main 方法中创建多个顾客线程和一个服务员线程,使用 join 方法确保所有顾客点餐完成后,服务员才开始准备餐食。
Customer类
public class Customer implements Runnable, Comparable<Customer> {private int name;public Customer(int name) {this.name=name;}public int getName() {return name;}public void setName(int name) {this.name=name;}@Overridepublic void run() {System.out.println("顾客"+getName()+" 发出点餐请求!");}@Overridepublic int compareTo(Customer other) {return Integer.compare(getName(),other.getName());}
}
Waiter类
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class Waiter implements Runnable {private List<Customer> customers = new ArrayList<>();public void addCustomer(Customer customer){customers.add(customer);}public void sortCustomer(){Collections.sort(customers);}@Overridepublic void run() {for (Customer customer : customers) {System.out.println("服务员处理 顾客"+customer.getName()+" 的订单");}System.out.println("服务员开始准备餐食!");}
}
Test
public class Test {public static void main(String[] args) throws InterruptedException {Thread [] customerThreads = new Thread[5];Waiter waiter = new Waiter();Thread waiterRun = new Thread(waiter);//创建、添加顾客for (int i=0; i < customerThreads.length; i++) {Customer customer = new Customer(i+1);customerThreads[i] = new Thread(customer);waiter.addCustomer(customer);}//顾客排序waiter.sortCustomer();//启动顾客点餐for (int i=0; i < customerThreads.length; i++) {customerThreads[i].start();}//等待顾客执行完毕for (Thread customerThread : customerThreads) {customerThread.join();}//服务员开始执行waiterRun.start();waiterRun.join();}
}
输出结果:
题目 2:模拟十字路口交通
场景:十字路口有东西和南北两个方向的车辆(线程),每个方向的车辆交替通过路口,每次通行一段时间(使用 sleep 模拟)。当一个方向的车辆通行时,另一个方向的车辆需要等待(使用 yield 让出 CPU 资源)。
要求:
- 创建 Vehicle 类实现 Runnable 接口,每个车辆线程在构造时传入行驶方向(如 "东西" 或 "南北"),线程任务是循环模拟车辆通过路口的过程。
- 在 Vehicle 类的 run 方法中,使用 yield 让当前方向车辆通行时,另一个方向的车辆等待。
- 在 main 方法中创建两个车辆线程,分别代表东西和南北方向的车辆,并启动线程观察交替通行的效果。
Vehicle类(假设跑10次,每2次礼让)
public class Vehicle implements Runnable{private String direction;public Vehicle(String direction) {this.direction=direction;}public String getDirection() {return direction;}public void setDirection(String direction) {this.direction=direction;}@Overridepublic void run() {for (int i=0; i < 10; i++) {System.out.println(getDirection()+" 方向的车辆开始通行!");try {Thread.sleep(250);} catch (InterruptedException e) {e.printStackTrace();}if (i%2 == 0){Thread.yield();System.out.println(getDirection()+" 正在礼让另一方向的车辆");}}}
}
Test
public class Test {public static void main(String[] args) {Vehicle vehicle1 = new Vehicle("东西");Vehicle vehicle2 = new Vehicle("南北");Thread vehicleEW = new Thread(vehicle1);Thread vehicleNS = new Thread(vehicle2);vehicleEW.start();vehicleNS.start();}
}
输出结果: