我正在调查setText的死锁问题,但首先需要学习和了解死锁。为此,我创建了一个简短的程序来尝试复制可能在更大范围内发生的情况,但我不确定为什么我的小程序从未发生死锁。
以下是我的学习程序:
public static void main(String[] a)
{
JFrame frame = new JFrame();
final JTextField p = new JTextField("start");
JButton btn = new JButton("button");
btn.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
p.setText(String.valueOf(System.nanoTime()));
}
});
}
});
frame.getContentPane().setLayout(new FlowLayout());
frame.getContentPane().add(p);
frame.getContentPane().add(btn);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
我认为不能在单独的线程中修改Swing,因此我在invokeLater
中设置了setText以在按钮点击时更改JTextField。这样做应该会违反单线程规则,这不会导致死锁吗?