下面是一个简单的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) 我想取消正在运行的任务并将其替换为同一线程上的新任务。
在下面的代码中,我使用了一个单线程执行器来启动一个新任务并捕获一个Future代表它的。然后我用Future取消了任务。但是,任务并没有取消。
示例代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
class Task implements Runnable {
public void run() {
System.out.println("New task started");
int i = 0; while (true) i++;
}
}
public class TaskLauncher extends JFrame {
private JButton button = new JButton("Start new task");
private ExecutorService executor = Executors.newSingleThreadExecutor();
private Future<?> future;
public TaskLauncher() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) …Run Code Online (Sandbox Code Playgroud)