【问题标题】:Java: How keep running process in thread and read it's values?Java:如何继续在线程中运行进程并读取它的值?
【发布时间】:2012-02-23 11:16:18
【问题描述】:

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

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

所以我认为,当用户点击“阅读”时,我会启动一个线程,这是因为用户可以在不冻结应用程序的情况下做另一件事。 但我无法访问该线程读取的值。

还有其他方法吗?

编辑:

    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)。

【问题讨论】:

  • 我不明白这个问题。 “无法访问此线程读取的值”是什么意思?
  • @m0skit0 我更新了我的帖子,希望我现在更清楚;)

标签: java multithreading swing thread-safety


【解决方案1】:

传递对您拥有的接口的引用。例如。您可以将 JFrame owner 字段添加到 Supervisory 类并在那里传递您的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多