繼SHG建議:
public MyStaticClass {
// from your question is not clear whether you need a static or non static List
// I will assume a static variable is ok
// the right-hand member should be enough to synchornize your ArrayList
public static List<String> myarray = Collections.synchronizedList(new ArrayList<String>());
public static void main(String[] args) {
// your stuff (which contains scanner initialization?)
ArrayList<String> myarray = new ArrayList<>();
while(scan.hasNextLine()){
myarray.add(scan.nextLine());
}
scan.close();
// your stuff (which contains thread initialization?)
}
但如果你真的需要一個非靜態變量
public MyClass {
private final List<String> myarray;
public MyClass() {
// the right-hand member should be enough to synchornize your ArrayList
myarray = Collections.synchronizedList(new ArrayList<String>());
}
public void getArray() {
return myarray;
}
public static void main(String[] args) {
// your stuff (which contains scanner initialization?)
Myclass myObj = new MyClass();
List<String> myObjArray = myObj.getArray();
while(scan.hasNextLine()){
myObjArray.add(scan.nextLine());
}
scan.close();
// your stuff (which contains thread initialization?)
}
有關細節靜態與非靜態字段看看Oracle documentation(基本上,你會或不會需要一個MyClass
實例獲得myarray
訪問權限,但是您將或不會在JVM中擁有不同的列表)。
只需將其分配給一個類成員,併爲其創建一個公共getter。然後你可以在任何地方使用這個數組。如果我們正在討論話題,你可能想同步它。 – SHG
你能否詳細說明你的問題。有一件事ArrayList不是線程安全的,不應該在多線程訪問它時使用。 –
如何使用同步的單例對象訪問此數組列表 –