有两个 Web 服务在提供实时库存的应用程序中运行。我必须编写一个java多线程程序从这两个接口(interface)读取库存并计算总库存。
前置条件:两个线程都必须立即启动。
我尝试使用下面的代码来解决这个问题。请检查并告诉我这是否正确。还有另一种可用的替代方法。
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();
}
}
}
最佳答案
将 Inventory.inventory
更改为 AtomicLong
。这样你就不需要同步 InventoryInterface1 & InventoryInterface2
Inventory
实例
class Inventory {
private AtomicLong inventory = new AtomicLong();
public long getInventory() {
return inventory.longValue();
}
public void incrementInventory(long inventory) {
inventory.addAndGet(inventory);
}
}
问题是在 Java
中读取和写入 long
不需要是原子的。 AtomicLong 的 addAndGet
是一个原子操作。
这里修改了InventoryInterface1
和InventoryInterface2
class InventoryInterface1 implements Runnable {
private Inventory inv;
public InventoryInterface1(Inventory inv) {
this.inv = inv;
}
public void run() {
System.out.println(Thread.currentThread().getName() + " running");
System.out.println(Thread.currentThread().getName() + " updates inventory");
inv.incrementInventory(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");
System.out.println(Thread.currentThread().getName() + " updates inventory");
inv.incrementInventory(200);
}
}
关于java - 如何使用多线程聚合两个 Web 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378683/