当我通过另一个线程保存她的数组列表时,为什么我不能显示它?

你好,我在显示外部类的列表时遇到问题。我尝试使用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();
            }
        }
    }
}
lipanhaoran 回答:当我通过另一个线程保存她的数组列表时,为什么我不能显示它?

这实际上取决于您何时以及如何开始致电o.show()。由于此列表是可变的,并且不固定。如果您确定在o.show之后致电o.bufferedReaderCollection();

,它将显示期望值。

-----------更新--------------- 基本上,以下流程应该适合您。

Thread t = new Thread(new CreateList());
t.start();
try{
  t.join();
} catch (Exception e){
  e.printStackTrace();
}
System.out.println(bufferedReaderClientLIst);

,

问题很简单,您的方法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();
            }
        }
    }
}

但是您还应该研究线程同步以同时访问列表。

本文链接:https://www.f2er.com/2966737.html

大家都在问