在提供实时库存的应用程序中运行有两个Web服务。我必须编写一个java多线程程序来从这两个接口读取清单并计算总库存。如何使用多线程来聚合两个Web服务?
前提条件:两个线程都必须毫不迟延地启动。
我试着用下面的代码来解决这个问题。请检查并告诉我这是否正确。还有另一种可用的替代方法。
package com.app.thread;
public class InventoryThread {
public static void main(String a[]) throws InterruptedException {
Inventory inv = new Inventory();
InventoryInterface1 i1 = new InventoryInterface1(inv);
InventoryInterface2 i2 = new InventoryInterface2(inv);
Thread t1 = new Thread(i1, "T1");
Thread t2 = new Thread(i2, "T2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(inv.getInventory());
}
}
class Inventory {
private long inventory;
public long getInventory() {
return inventory;
}
public void setInventory(long inventory) {
this.inventory = inventory;
}
}
class InventoryInterface1 implements Runnable {
private Inventory inv;
public InventoryInterface1(Inventory inv) {
this.inv = inv;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " running");
synchronized (inv) {
System.out.println(Thread.currentThread().getName() + " updates inventory");
inv.setInventory(inv.getInventory() + 100);
}
}
}
class InventoryInterface2 implements Runnable {
private Inventory inv;
public InventoryInterface2(Inventory inv) {
this.inv = inv;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " running");
synchronized (inv) {
try {
System.out.println(Thread.currentThread().getName() + " waiting..");
while(inv.getInventory() <= 0){
inv.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " updates inventory");
inv.setInventory(inv.getInventory() + 200);
System.out.println(Thread.currentThread().getName() + " notifies");
inv.notifyAll();
}
}
}
我建议你先阅读并发教程。在你的例子中有一些错误,在本质上需要一个教程,如答案 –
@loannis我正在学习Java的并发性,并希望获得专家输入的问题,我被要求解决。谢谢! – Vel