您好,我在从外部类显示列表时遇到问题。我尝试使用 public void show() 方法,但列表为空。我认为问题出在线程上,这可能吗?谁能解释为什么会发生这种情况?
public class CollectionsOperation
{
private List<Client> bufferedReaderClientLIst =
Collections.synchronizedList(new ArrayList<Client>());
BufferedReader bf = null;
private static final String fileName = "clients.txt";
public void bufferedReaderCollection()
throws IOException
{
String line;
try {
bf = new BufferedReader(new InputStreamReader(
new FileInputStream(fileName), "UTF-8"));
while ((line = bf.readLine()) != null) {
String[] split = line.split(";");
String nameCompany = split[0].substring(2);
String adress = split[1];
String phoneNumber = split[2];
String emailAdress = split[3];
Client k = new Client(nameCompany, adress, phoneNumber, emailAdress);
bufferedReaderClientLIst.add(k);
}
} catch (IOException e) {
}
}
public void runBufferedReader()
{
Thread t = new Thread(new CreateList());
t.start();
}
public void show()
{
System.out.println(bufferedReaderClientLIst);
}
private class CreateList implements Runnable
{
@Override
public void run()
{
CollectionsOperation o = new CollectionsOperation();
try {
o.bufferedReaderCollection();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
最佳答案
问题很简单,您的方法 CreateList::run
创建了 CollectionsOperation
的新实例。因此,原始对象方法 show
将不会访问与 CreateList
类填充的列表相同的数据。
相反,您可能想使用
public void run()
{
CollectionsOperation.this.bufferedReaderCollection();
}
另一种方法是在 CreateList
中创建一个构造函数,并使用 CollectionsOperation
对象作为参数。
public class CollectionsOperation
{
...
public void runBufferedReader()
{
Thread t = new Thread(new CreateList(this));
t.start();
}
...
private class CreateList implements Runnable
{
CollectionsOperation co;
public CreateList(CollectionsOperation co) {
this.co = co;
}
@Override
public void run()
{
try {
co.bufferedReaderCollection();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
但是您还应该考虑线程同步以实现对列表的并发访问。
关于java - 当我通过另一个线程保存她时,为什么我无法显示我的 arrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59203820/