[英]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.