- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是情况,代码如下
用户填写 3 个字段并按“添加”按钮
=> 创建一个 ToDoBean 并将其添加到 ToDoModel(扩展 AbstractTableModel)
并使用模型中 ToDoBean 的索引创建一个 Runnable。
Runnable 通过 ScheduledExecutorService 立即启动。
Runnable 的目标是递减一个 int 直到它达到零。
一切正常。
现在,用户还可以在 JTable 中选择一行,然后按“删除”按钮从列表中删除 ToDoBean。
我的问题是:当我删除 bean 时,它看起来也从 ScheduledExecutorService 中删除。为什么?如何?
事实上,这正是我所需要的,但我想了解其机制。
谢谢
编码:
package demo.todolist;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class ToDoFrame extends javax.swing.JFrame {
private final static int POOL_SIZE = 10;
private ToDoModel model = new ToDoModel();
private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(POOL_SIZE);
/** Creates new form ToDoFrame */
public ToDoFrame() {
initComponents();
}
private ToDoBean createToDoBean() {
return new ToDoBean(jTextField1.getText(), jTextField2.getText(), Long.valueOf(jTextField3.getText()));
}
private void addToList(ToDoBean toDoBean) {
model.addToDoBean(toDoBean);
scheduledExecutorService.schedule(new UpdateRunnable(model.getRowCount() - 1), 0,TimeUnit.SECONDS);
}
private class UpdateRunnable implements Runnable {
private int index;
public UpdateRunnable(int index) {
this.index = index;
}
@Override
public void run() {
System.out.println("Task for index " + index + " started");
while (model.getToDoBeanAt(index).getDelay() > 0) {
try {
Thread.sleep(10000);
model.decreaseBeanAt(index);
System.out.println("Delay decreased at index " + index);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
System.out.println("Task for index " + index + " ended");
}
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
GridBagConstraints gridBagConstraints;
jLabel1 = new JLabel();
jLabel2 = new JLabel();
jLabel3 = new JLabel();
jTextField1 = new JTextField();
jTextField2 = new JTextField();
jTextField3 = new JTextField();
jButton1 = new JButton();
jScrollPane1 = new JScrollPane();
jTable1 = new JTable();
jButton2 = new JButton();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridBagLayout());
jLabel1.setText("Name :");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.anchor = GridBagConstraints.LINE_END;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jLabel1, gridBagConstraints);
jLabel2.setText("Description :");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.anchor = GridBagConstraints.LINE_END;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jLabel2, gridBagConstraints);
jLabel3.setText("Delai (seconds) :");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = GridBagConstraints.LINE_END;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jLabel3, gridBagConstraints);
jTextField1.setText("my name ");
jTextField1.setMinimumSize(new Dimension(50, 25));
jTextField1.setPreferredSize(new Dimension(80, 27));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.anchor = GridBagConstraints.LINE_START;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jTextField1, gridBagConstraints);
jTextField2.setText("some description");
jTextField2.setMinimumSize(new Dimension(145, 25));
jTextField2.setPreferredSize(new Dimension(145, 27));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 2;
gridBagConstraints.anchor = GridBagConstraints.LINE_START;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jTextField2, gridBagConstraints);
jTextField3.setHorizontalAlignment(JTextField.TRAILING);
jTextField3.setText("5");
jTextField3.setMinimumSize(new Dimension(25, 25));
jTextField3.setPreferredSize(new Dimension(25, 27));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 2;
gridBagConstraints.anchor = GridBagConstraints.LINE_START;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jTextField3, gridBagConstraints);
jButton1.setText("Add");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
getContentPane().add(jButton1, new GridBagConstraints());
jScrollPane1.setMinimumSize(new Dimension(280, 150));
jScrollPane1.setPreferredSize(new Dimension(280, 275));
jTable1.setModel(model
);
jScrollPane1.setViewportView(jTable1);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 3;
gridBagConstraints.gridwidth = 3;
getContentPane().add(jScrollPane1, gridBagConstraints);
jButton2.setText("Remove");
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 2;
gridBagConstraints.gridy = 2;
gridBagConstraints.insets = new Insets(5, 5, 5, 5);
getContentPane().add(jButton2, gridBagConstraints);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(ActionEvent evt) {
addToList(createToDoBean());
}
private void jButton2ActionPerformed(ActionEvent evt) {
int rowIndex = jTable1.getSelectedRow();
model.removeToDoBeanAt(rowIndex);
/*
* the ToDoBean is removed from the list
* the table is updated
* the scheduledExecutorService is also updated ... why?
*/
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ToDoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ToDoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ToDoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ToDoFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ToDoFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private JButton jButton1;
private JButton jButton2;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JScrollPane jScrollPane1;
private JTable jTable1;
private JTextField jTextField1;
private JTextField jTextField2;
private JTextField jTextField3;
// End of variables declaration
}
package demo.todolist;
import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel;
public class ToDoModel extends AbstractTableModel {
protected List<ToDoBean> list = new ArrayList<ToDoBean>();
private final static String[] columns = {"Name", "Description", "Remaining"};
private final static Class[] columnsClass = {String.class, String.class, Long.class};
public final static int[] columnWidths = {80, 150, 50}; // 280
public ToDoModel() {
}
public ToDoModel(List<ToDoBean> list) {
super();
this.list = list;
}
@Override
public Class getColumnClass(int columnIndex) {
return columnsClass[columnIndex];
}
@Override
public int getRowCount() {
return list.size();
}
@Override
public int getColumnCount() {
return columns.length;
}
@Override
public String getColumnName(int col) {
return columns[col];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
ToDoBean result = list.get(rowIndex);
switch (columnIndex) {
case 0:
return result.getName();
case 1:
return result.getDescription();
default:
return result.getDelay();
}
}
@Override
public void setValueAt(Object obj,int rowIndex, int columnIndex) {
ToDoBean result = list.get(rowIndex);
switch (columnIndex) {
case 0:
result.setName((String) obj);
break;
case 1:
result.setDescription((String) obj);
break;
default:
result.setDelay((Long) obj);
}
list.set(rowIndex, result);
this.fireTableCellUpdated(rowIndex, columnIndex);
}
public void addToDoBean(ToDoBean w) {
list.add(w);
fireTableDataChanged();
}
public void addToDoBeanList(List l) {
list.addAll(l);
fireTableDataChanged();
}
public ToDoBean getToDoBeanAt(int row) {
return list.get(row);
}
public ToDoBean removeToDoBeanAt(int row) {
ToDoBean pos = list.remove(row);
fireTableDataChanged();
return pos;
}
public long decreaseBeanAt(int rowIndex) {
ToDoBean result = list.get(rowIndex);
long remaining = result.getDelay();
result.setDelay(--remaining);
this.fireTableCellUpdated(rowIndex, 2);
return remaining;
} }package demo.todolist;
public class ToDoBean {
private String name;
private String description;
private long delay;
public ToDoBean(String name, String description, long delay) {
this.name = name;
this.description = description;
this.delay = delay;
}
public ToDoBean() {
}
public long getDelay() {
return delay;
}
public void setDelay(long delay) {
this.delay = delay;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void decrease() {
delay--;
} }
最佳答案
我偶然发现了你的问题,我有一个很好的解决方案。使用 ScheduledThreadPoolExecutor .它将允许您安排任务并在不再需要它们时将其删除。
关于scheduledexecutorservice - 从 ScheduledExecutorService 中删除 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13425898/
这是情况,代码如下 用户填写 3 个字段并按“添加”按钮 => 创建一个 ToDoBean 并将其添加到 ToDoModel(扩展 AbstractTableModel) 并使用模型中 ToDoBea
Quarkus 有一个 https://quarkus.io/guides/scheduler来安排任务。但是,我想使用 ScheduledExecutorService .这在夸克中是允许的吗?例如
我有以下代码: ScheduledExecutorService scheduledExecutor; ..... ScheduledFuture result = scheduledExecutor
我需要实现一个计划执行程序服务,该服务每隔 x 秒运行一个线程。如果线程执行时间超过 y 秒,则应中断线程执行。我尝试使用 ScheduledExecutorService 来实现该解决方案,该服务具
我正在创建一个新线程来检查文件夹中是否有新文件,然后 hibernate 一段定义的时间。 我的首选是使用 ScheduledExecutorService,但是,我找不到任何文档来说明这是否需要等待
如何让 ScheduledExecutorService 在给定时间段内以给定时间速率执行任务? 然后下面的代码将使其以 1 秒的速率执行...但是我如何限制所有这些重复的总周期 service.sc
我意识到,如果在我的可运行对象的 run 方法内部(或没有,但应该与之相关)引发异常,我 future 的所有任务都将不会运行。 所以我的问题是:我如何从这样的异常中恢复(在哪里捕获它)? 我已经尝试
我正在使用预定执行程序服务 私有(private) ScheduledExecutorService 池 = new ScheduledThreadPoolExecutor(1); 以固定速率运行可运
ScheduledExecutorService ScheduledExecutorService 是在主线程还是后台线程上运行,我经历了 documentation here 但没有找到。 任何帮助
我有一个耳朵,将作为后端耳朵部署在多个服务器上。在那个耳朵中,我需要添加 ScheduledExecutorService 以在特定时间从数据库中获取一些记录并处理它们。但我只需要处理一次,而不是在将
我有 ScheduledExecutorService,我正在尝试更新内部数据但没有结果 public void myMethod(final String myString) { myExe
我目前遇到了 ScheduledExecutorService 执行速度快于给定时间范围的问题。 scheduleAtFixedRate声明后续执行可能会延迟,但不会等待给定的时间。 GrabPutT
我正在使用 ScheduledExecutorService.scheduleWithFixedDelay() 来安排线程的定期启动。它可以工作,但线程正在 ThreadStackTrace 中累积(
我有以下代码,每 20 分钟后调用一次任务,并且工作正常。现在,在此之上,我希望它仅在 0900 到 1800 之间工作 ScheduledExecutorService scheduler = Ex
我有一个特定的任务,必须定期执行,或者根据条件仅执行一次。我正在使用以下方法: Runnable r = new Runnable() { public void run()
我有一个 ScheduledExecutorService 来获取定期执行的任务: scheduler = Executors.newScheduledThreadPool( what size? )
以下代码是从 JMenuItem 的 ActionListener 调用的。它只是启动一个 jar 文件。 ScheduledExecutorService schedulerExecutor = E
我有两个每秒运行的执行器服务。但是当我在 run 方法中插入一行代码时,其中一个会停止运行。这是我的类(class): 游戏服务器: public class GameServer implement
提出此问题的动机我正在运行一个在非常昂贵的硬件上运行的大型产品。出于测试目的而关闭它是不可能的,也不可能在生产环境中放置一个坏的 jar。我需要尽可能确保几乎确保我不会弄乱生产环境。 在暂存设置上运行
已关闭。此问题需要 debugging details 。目前不接受答案。 编辑问题以包含 desired behavior, a specific problem or error, and the
我是一名优秀的程序员,十分优秀!