0
我想要生成客戶對象並將它們存儲在ArrayList中,但我不能。如何通過Java中的線程將項目添加到ArrayList
這裏是我的客戶類
public class Customer {
private int customerID;
private int processTime;
ArrayList<Integer> customerIDList = new ArrayList<>();
ArrayList<Integer> processTimeList = new ArrayList<>();
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public int getProcessTime() {
return processTime;
}
public void setProcessTime(int processTime) {
this.processTime = processTime;
}
public ArrayList<Integer> getCustomerIDList() {
return customerIDList;
}
public void setCustomerIDList(ArrayList<Integer> customerIDList) {
this.customerIDList = customerIDList;
}
public ArrayList<Integer> getProcessTimeList() {
return processTimeList;
}
public void setProcessTimeList(ArrayList<Integer> processTimeList) {
this.processTimeList = processTimeList;
}
}
CustomerThread類,這是產生顧客對象10倍和兩個客戶100之間毫秒
public class CustomerThread extends Thread {
Customer c = new Customer();
Methods method = new Methods();
@Override
public void run() {
for(int i = 1; i <= 10; i++) {
try {
//c.setCustomerID(i);
//c.setProcessTime(method.generateProcessTime());
c.getCustomerIDList().add(i);
c.getProcessTimeList().add(method.generateProcessTime());
System.out.println("ID : " + c.getCustomerIDList().get(i) + " - Process Time : " + c.getProcessTimeList().get(i));
Thread.sleep(100);
}
catch (InterruptedException ex) {
Logger.getLogger(CustomerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
generateProcessTime的方法是隨機生成INT數,沒有問題。 這裏是我的測試類
public class Test {
public static void main(String[] args) {
CustomerThread ct = new CustomerThread();
ct.start();
}
}
當我執行這些,會發生這種錯誤,
異常在線程 「線程0」 java.lang.IndexOutOfBoundsException:指標:1,規格:1
非常感謝! – MrBoolean