在使用多线程时选择Runnable接口,如何遍历调用该类中的方法。
以下是主类中的两个方法和一个出售点类,想通过遍历Thread数组来寻找其中一个出售点并唤醒,该如何编写notifyPurchasePoint方法
for (int i = 0; i < purchase.length; i++) {
purchase[i] = new Thread(new StoreHouseIn(i, this));
}
public synchronized void notifyPurchasePoint(int itemId) {
for (int i = 0; i < purchase.length; i++) {
}
}
public class StoreHouseIn implements Runnable {
private final int id;
private static StoreHouse storeHouse;
private Random random;
public StoreHouseIn(int id, StoreHouse storeHouse) {
this.id = id;
StoreHouseIn.storeHouse = storeHouse;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
synchronized (this) {
wait();
}
int quantity = random.nextInt(10) + 10;
StoreHouse.purchase(itemId, quantity);
}
} catch (InterruptedException e) {
System.out.println("商品" + id + "停止采购");
}
}
public int getId() {
return id;
}
可以在StoreHouseIn类中添加一个方法,用于唤醒该出售点的线程。然后在notifyPurchasePoint方法中遍历Thread数组,找到对应的出售点线程并调用该方法唤醒它。
具体实现如下:
在StoreHouseIn类中添加一个方法:
public synchronized void wakeUp() {
notify();
}
在notifyPurchasePoint方法中遍历Thread数组,找到对应的出售点线程并调用wakeUp方法唤醒它:
public synchronized void notifyPurchasePoint(int itemId) {
for (int i = 0; i < purchase.length; i++) {
if (purchase[i] instanceof StoreHouseIn && ((StoreHouseIn) purchase[i]).getId() == itemId) {
((StoreHouseIn) purchase[i]).wakeUp();
break;
}
}
}
这样就可以通过遍历Thread数组来寻找对应的出售点线程并唤醒它了。
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!