简体   繁体   中英

How to synchronize thread pool?

my homework is about implementing an application that through threads allows me to search for a file in different folders the threads will create a ring topology, where each thread has interaction with the successor and predecessor thread.. but first I would like to print the id of the current node, the next one, and the previous one on my jframe.

The user specific how many threads he want to use, and that's the number of independent windows will be create.

But my question is, how do I know that? I think if I do that inside the for cycle using 'i' and increment it, like i+1, to print the following isn't the correct way.

this is my constructor where I am giving the index of the for cycle then I have my Run method to print it to a 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");
        }

// This is other class

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 is single-threaded. Don't do this with an ExecutorService. Use the Swing Timer instead. Something like:

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();
    }
}    

I've let it for you to fill in the scheduledAtFixedRate parameters, as well as work out when/how to stop the timer action

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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