リアルタイムインベントリを提供するアプリケーションには、2つのWebサービスが実行されています。私は、これらの2つのインターフェイスから在庫を読み取り、総在庫を計算するJavaマルチスレッドプログラムを書く必要があります。マルチスレッドを使用して2つの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();
}
}
}
InventoryInterface1
とInventoryInterface2
を修正しています。あなたの例で間違っている点がいくつかあります。答えのようなチュートリアルが必要です。 –@loannis私はJavaの並行性を学んでおり、解決するように求められた問題の専門家の入力を得たいと思っていました。ありがとう! – Vel