在线程运行时使用OSGi控制台

时间:2015-08-03 23:29:57

标签: java multithreading console osgi

我目前正在使用OSGi来开发一个定期从某些传感器获取数据的数据管理器。我获取数据的方式如下:

public void run() {
        while (!stop || !Thread.currentThread().isInterrupted()) {
            try {
                List<DataEntry> aux;
                long millis = System.currentTimeMillis();
                for (DataLogger dl : loggers) {
                    String name = dl.getDriverName();
                    aux = dataTable.get(name);
                    if (aux == null) {
                        aux = new ArrayList<DataEntry>();
                    }
                    dl.readValue();
                    DataEntry de = new DataEntry(dl.getCurrentValue(), millis);
                    aux.add(de);
                    dataTable.put(dl.getDriverName(), (ArrayList<DataEntry>) aux);
                }
                Thread.sleep(PERIOD);


            // ***** Exceptions *****
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

我遇到的问题是console正在运行时我无法与thread进行交互,这意味着我无法从控制台停止捆绑执行并与之交互执行。

有没有办法让bundle在与主要线程不同的线程中运行?

***更新: 我直接调用run方法,而不是启动线程,这就是问题。

1 个答案:

答案 0 :(得分:1)

您已经省略了代码中最重要的部分,即run()方法实际执行的方式。它被称为run()的事实表明该方法在一个实现Runnable的类中,而这反过来又表明你实际上是在启动一个新的Thread()来执行它。但是我猜你的问题是你实际上没有这样做并直接从启动bundle的线程运行方法(从BundleActivator&#39; start()方法调用它)。如果确实如此,则不会启动其他捆绑包,此捆绑包将保持STARTING状态。要解决这个问题,请生成一个新的Thread。

但我可能会离开,请发布您的其余代码! :)