我尝试选择按钮来执行客户端或服务器布局,但是当我单击服务器按钮时,发生了动作函数在13个线程中执行服务器,导致锁定布局,
我不知道为什么点击执行了其他线程?
/*
main is thread 1 doing this task,but button action is thread 13 doing this task
*/
public class Main {
public static void main(String args[]) {
long threadId = Thread.currentThread().getId();
System.out.println("Thread # " + threadId + " is doing this task");
new Main().view();
}
private void view() {
JFrame jFrame = new JFrame("Server");
JPanel jPanel = new JPanel();
JButton jButton = new JButton("test");
jFrame.setLocation(300, 300);
jPanel.setPreferredSize(new Dimension(350, 300));
GroupLayout groupLayout=new GroupLayout(jPanel);
jPanel.setLayout(groupLayout);
groupLayout.setHorizontalGroup(
groupLayout.createSequentialGroup()
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton,0,groupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
groupLayout.setVerticalGroup(
groupLayout.createSequentialGroup()
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(groupLayout.createParallelGroup()
.addComponent(jButton,0,groupLayout.DEFAULT_SIZE,GroupLayout.PREFERRED_SIZE))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED,
GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
long threadId = Thread.currentThread().getId();
System.out.println("Thread # " + threadId + " is doing this task");
}
});
jFrame.add(jPanel);
jFrame.pack();
jFrame.setFocusable(true);
jFrame.setEnabled(true);
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我该如何解决这个问题?
答案 0 :(得分:1)
在你的主要:
public static void main(String args[]) {
long threadId = Thread.currentThread().getId();
System.out.println("Thread # " + threadId + " is doing this task");
}
当前线程是初始线程,即启动应用程序的线程。
在你的按钮中:
jButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
long threadId = Thread.currentThread().getId();
System.out.println("Thread # " + threadId + " is doing this task");
}
当前线程是EDT(事件调度线程)。这是Swing用来管理事件的线程。
您可以在Lesson: Concurrency in Swing中找到更多信息。阅读会很好,因为有一些"规则"使用Swing
时关注。每个事件(点击,更新,...)都在EDT中完成。如果你在其中进行长时间处理,它将冻结GUI。