继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不是线程安全的,不应该在多线程访问它时使用。 –
如何使用同步的单例对象访问此数组列表 –