我在编写架构原型时遇到了一个奇怪的问题。
我试图创建两个独立调度相同命令的线程。第一个线程是使用a Scanner
,第二个线程是依赖Swing。问题是第一个线程阻止了第二个线程启动。第二个线程仅在扫描仪获得足够的输入后才开始。强制第一个线程休眠直到第二个线程启动也暂时解决了这个问题。
下面的示例非常一致地重现了此行为。在通话之间休眠使其更加一致。
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
public final class Bug {
public static void main(final String[] arguments) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("The commands are \"wait\" and \"quit\".");
final Scanner scanner = new Scanner(System.in);
loop: while (true) {
System.out.print("Enter a command: ");
final String command = scanner.nextLine();
switch (command.toLowerCase()) {
case "exit":
case "quit":
break loop;
default:
System.out.println("Use \"wait\" or \"quit\" instead of \"" + command + "\".");
case "wait":
}
}
scanner.close();
}
}).start();
try {
Thread.sleep(1000);//improves consistency
}
catch (final InterruptedException exception) {}
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
final JFrame frame = new JFrame("Commands");
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setResizable(false);
frame.setLayout(new BorderLayout());
frame.add(new JButton("Wait"), BorderLayout.LINE_START);
final JButton button = new JButton("Quit");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent event) {
frame.dispose();
}
});
frame.add(button, BorderLayout.LINE_END);
frame.pack();
frame.setVisible(true);
}
});
}
}
为什么第二个线程不能正常启动?是我的错吗?
十多年前,一个类似的问题作为错误提交。
运行java -version
结果
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) Client VM (build 23.21-b01, mixed mode, sharing)
并且cmd -info
在
Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.
如果这很重要。