这是我创建的用于管理仓库库存的基本应用程序。基本上五个线程或 IT 公司每个生产 100 个小部件,然后将其存储在仓库中。这很好用,但偶尔会超过 500 个的仓库限制。所以我希望五个独立的公司分别生产 100 个小部件并将它们存储在仓库中,并停止在 500 个小部件。然而,目前它有时但并不总是超过限制。因此,如果我运行它 3 次,它会工作 2/3,它只会不断地向仓库中添加无穷无尽的小部件。所以我的问题是我该如何解决这个问题?
这是代码
public class mainClass {
public static void main(String[] args) {
warehouse acct1 = new warehouse(0); // create warehouse with nothing in it
System.out.print("Reciving widgets...");
acct1.checkBal();
manufacturer t1 = new manufacturer(acct1, "Calcutta"); // create 5 threads (manufacturers)
manufacturer t2 = new manufacturer(acct1, "New York");
manufacturer t3 = new manufacturer(acct1, "Chicargo");
manufacturer t4 = new manufacturer(acct1, "Liverpool");
manufacturer t5 = new manufacturer(acct1, "Tokyo");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
制造商类
import java.util.*;
public class manufacturer extends Thread {
warehouse myAcct; //class 'warehouse' assigned to variable MyAcct
String name;
int time;
Random r = new Random(); // imported from java.util this can be used to create a random amount of time
int amount = 100; // This variable is the manufacturing goal of each individual manufacture (thread)`
public manufacturer(warehouse acct, String x) {
myAcct = acct;
name = x; // name of the thread
time = r.nextInt(4000); // This creates the random time of anywhere between 0 and 9999
}
public void run() {
while (true) { // run forever
try {
sleep (time); // Create new widgets
} catch (InterruptedException e) { }
// 100 by each manufacturer
try{
Thread.sleep(time);
System.out.printf("%s has successfully manufactured %d widgets \n", name, amount);
//how long do u want to sleep for?
//System.out.printf("%s is done\n", name);
myAcct.adjustBal(100); System.out.println("widgets have been stored at the central warehouse");
System.out.println();
Thread.sleep(time);
}catch(Exception e){}
if (myAcct.getBal() == 500)
{
System.out.println("The target goal of 500 widgets have been created and delivered to the central warehouse");
System.exit(0);
//myAcct.adjustBal(100);// with 100 if necessary
}
}
}
}
public class warehouse {
int balance = 0;
public warehouse(int openingBal) { // constructor method
balance = openingBal;
}
public synchronized void adjustBal(int amt) {
balance += amt; // process a transaction
checkBal(); // then show the balance
}
public void checkBal() {
System.out.print (balance);
System.out.println();
}
public int getBal() {
return balance;
}
}