繁体   English   中英

如何同步线程池?

[英]How to synchronize thread pool?

我的作业是关于实现一个应用程序,该应用程序允许我通过线程搜索不同文件夹中的文件,这些线程将创建一个环形拓扑,其中每个线程都与后继线程和前驱线程进行交互......但首先我想打印 id我的 jframe 上的当前节点、下一个和上一个节点。

用户指定他想使用多少个线程,这就是将创建的独立窗口的数量。

但我的问题是,我怎么知道? 我想如果我在 for 循环中使用 'i' 这样做并增加它,比如 i+1,打印以下内容不是正确的方法。

这是我的构造函数,我在其中给出 for 循环的索引,然后我有我的 Run 方法将它打印到 jframe

public tareaHilo(int id) {
    initComponents();
    this.idHilo = id;
}
public void run() {
            this.setVisible(true);
            numeroHilo.setText(Integer.toString(idHilo));
            nodoPrecedente.setText("previous one");
            nodoSubsecuente.setText("next one");
        }

// 这是其他类

private void botonCrearActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try {
        tareaHilo tarea;
        numHilos = Integer.parseInt(inputHilos.getText());
        ExecutorService ex = Executors.newFixedThreadPool(numHilos);
        for (i = 1; i <= numHilos; i++) {
            tarea = new tareaHilo(i);
            ex.execute(tarea);
        }
        this.setVisible(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

Swing 是单线程的。 不要使用 ExecutorService 执行此操作。 改用摇摆计时器。 就像是:

public tareaHilo(int id) {
    initComponents();
    this.idHilo = id;
}
int i;
public void actionPerformed(ActionEvent ae) {
            this.setVisible(true);
            numeroHilo.setText("" + i);
            i++;
            nodoPrecedente.setText("Hilo Anterior #");
            nodoSubsecuente.setText("Hilo Siguiente #");
        }

private void botonCrearActionPerformed(java.awt.event.ActionEvent evt) {                                           
    try {
        tareaHilo tarea;
        numHilos = Integer.parseInt(inputHilos.getText());
        javax.swing.Timer t = new javax.swing.Timer();
        t.scheduleAtFixedRate(...)
        this.setVisible(false);
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

我已经让你填写 scheduleAtFixedRate 参数,以及计算何时/如何停止计时器操作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM