這裏是我創建管理倉庫的庫存基本應用。基本上五個線程或IT公司每個產生100個小部件,然後將其存儲在倉庫中。這工作得很好,但偶爾也越過倉庫上限是500所以我要五個獨立的公司能夠生產每100個零件,並把它們存儲在倉庫中,並在500個部件停止。但目前它有時但並非總是超過極限。所以如果我要運行它三次,它將工作2/3,它會繼續添加endles的部件到倉庫。所以我的問題是如何解決這個問題?螺紋庫存控制
下面是代碼
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;
}
}
類名應以大寫字母開頭爲'MainClass' – Abubakkar
這看起來像一個家庭作業的問題。另外它的芝加哥,而不是Chicargo。 – monksy