如何从java线程获取变量值

时间:2021-08-14 00:31:33

I have a thread which computes something and generates a 2 d array. I need to access the value of this 2 d array, when the thread is finished. How can I do that

我有一个线程计算一些东西并生成一个2 d数组。线程完成后,我需要访问这个2 d数组的值。我怎样才能做到这一点

        SwingWorker<Integer, Void> worker = new SwingWorker<Integer, Void>()
        {
            Object[][] valueMatrix = null;

            @Override
            public Integer doInBackground()
            {
                try
                {
                    valueMatrix = doChemicalSynonyms(termsArray_1, termsArray_2, mView.getSaveFilepath(), false, mView.getSheetName(), mView.getCategoryName(), mView.includePMIDs());
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    return -1;
                }
                return 0;
            }

            @Override
            public void done()
            {
                System.out.println(valueMatrix[0][0]);
            }
        };
        worker.execute();

doChemicalSynonyms functions generates the valueMatrix. How can I access it once the thread is complete, from the main class( something like global variable)

doChemicalSynonyms函数生成valueMatrix。线程完成后如何从主类(类似全局变量)访问它

1 个解决方案

#1


-1  

what you should do is to use the done() method to collect any result from the thread. Basically where you are now printing the first value, you can transfer it to another thread to use it there.

你应该做的是使用done()方法从线程中收集任何结果。基本上你现在打印第一个值,你可以将它转移到另一个线程以在那里使用它。

Beware that the done() is invoked in the EDT, so if you need to do an intensive operariton on it, another thread is necessary.

请注意在EDT中调用done(),因此如果需要对其执行强化操作,则需要另一个线程。

#1


-1  

what you should do is to use the done() method to collect any result from the thread. Basically where you are now printing the first value, you can transfer it to another thread to use it there.

你应该做的是使用done()方法从线程中收集任何结果。基本上你现在打印第一个值,你可以将它转移到另一个线程以在那里使用它。

Beware that the done() is invoked in the EDT, so if you need to do an intensive operariton on it, another thread is necessary.

请注意在EDT中调用done(),因此如果需要对其执行强化操作,则需要另一个线程。