Java:如何在线程中继续运行进程并读取它的值?

时间:2012-02-23 11:16:18

标签: java multithreading swing thread-safety

我不知道这是否是最好的方法,所以这就是我问你帮助的原因。

这是我的问题,我正在开发一个应用程序,你有“读取”按钮,当用户点击此按钮然后程序开始读取一些值并将这些值保存在我的数据库中,好吗?

所以我认为当用户点击'read'时我会启动一个帖子,那是因为如果用户没有应用程序被冻结,用户可以做另一件事。 但我无法访问此线程读取的值。

还有另一种方法吗?

编辑:

    private void jtb_readerItemStateChanged(java.awt.event.ItemEvent evt) {                                            
        // getting some values provided by the user       

        if (buttonReaderState()){
            if (supervisory == null)
                supervisory = new Supervisory(ip, broadcast, deviceID);
                supervisory.start();
        }
    }                                           

// Supervisory class
    public void start(){
        Scan scan = new Scan();
        Thread t = new Thread(scan);
        t.start();
        threadState = true;
    }

    class Scan extends Thread{
        public void run(){
            // inside the tread I have to initiate another 'supervisory' object, is that right ? 
            Supervisory s = new Supervisory(ip, broadcast, deviceID);
            while (threadState){
                try {
                    s.active();

                } catch (IOException ioe) {
                    ioe.printStackTrace();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void active() throws IOException, Exception  {
        // getting this values from my hardware like temperature and anothers things.

        for (int i = 0; i < ois.size(); i++) {
            ObjectIdentifier oi = ois.get(i);

            //analog input
            if (i == 1)
                aI = Float.parseFloat(getPresentValue(localDevice, oi));
            //analog output
            if (i == 2)
                aO = Float.parseFloat(getPresentValue(localDevice, oi));
            //binary input
            if (i == 3)
                bI = getBinaryValue(getPresentValue(localDevice, oi));
            //binary output
            if (i == 4)
                bO = getBinaryValue(getPresentValue(localDevice, oi));
        }

    }

在读取这些值之后,我想在我正在构建的界面中显示这些值,但似乎我无法访问这些值(aI,aO,bI,bO)。

1 个答案:

答案 0 :(得分:2)

将引用传递给您拥有的界面。例如。您可以向监督类添加JFrame owner字段并在那里传递您的值。