我已经使用执行程序提交了一个任务,我需要它在一段时间后停止(例如5分钟).我试过这样做:
for (Future<?> fut : e.invokeAll(tasks, 300, TimeUnit.SECONDS)) {
try {
fut.get();
} catch (CancellationException ex) {
fut.cancel(true);
tasks.clear();
} catch(ExecutionException ex){
ex.printStackTrace(); //FIXME: gestita con printstack
}
}
Run Code Online (Sandbox Code Playgroud)
但我总是得到一个错误:我有一个需要被任务修改然后由线程读取的共享Vector,即使我停止所有任务,如果超时发生,我得到:
Exception in thread "Thread-1" java.util.ConcurrentModificationException
Run Code Online (Sandbox Code Playgroud)
有什么不对?如何停止提交的5分钟后仍在工作的任务?
下面是一个简单的Java Swing程序,它由两个文件组成:
图形用户界面显示"新游戏"按钮,然后显示编号为1到3的其他三个按钮.
如果用户点击其中一个编号按钮,游戏会将相应的数字打印到控制台上.但是,如果用户单击"新游戏"按钮,程序将冻结.
(1)为什么程序会冻结?
(2)如何重写程序来解决问题?
(3)如何更好地编写程序?
Game.java:
public class Game {
private GraphicalUserInterface userInterface;
public Game() {
userInterface = new GraphicalUserInterface(this);
}
public void play() {
int selection = 0;
while (selection == 0) {
selection = userInterface.getSelection();
}
System.out.println(selection);
}
public static void main(String[] args) {
Game game = new Game();
game.play();
}
}
Run Code Online (Sandbox Code Playgroud)
GraphicalUserInterface.java:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GraphicalUserInterface extends JFrame implements …Run Code Online (Sandbox Code Playgroud)