我用 java swing 编写了一个简单的程序,它假设启动另一个线程,在该线程中,当我单击一个按钮时,一个 JForm 将出现。但是 JForm 没有出现......当我评论程序运行时,我使用 if (Thread.currentThread().getName() == "Thread1")
为该线程执行特定任务完美,我不明白为什么它不会进入 if block ...请有人帮我解决这个问题...
提前致谢!
这是代码,
public class Test extends JFrame implements ActionListener {
JPanel panel;
JButton button;
public Test() {
setVisible(true);
setSize(300, 300);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
panel = new JPanel();
button = new JButton("click me");
button.addActionListener(this);
panel.add(button);
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Test tst=new Test();
}
@Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==button){
System.out.println("test");
test2 test = new test2();
Thread tr1 = new Thread(test);
tr1.setName("Thread1");
tr1.start();
}
}
}
class test2 implements Runnable{
public void run() {
//if (Thread.currentThread().getName() == "Thread1") {
System.out.println("inside thread");
JFrame frame2=new JFrame();
frame2.setVisible(true);
frame2.setSize(300, 300);
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//}
}
最佳答案
尝试使用 getName().equals("Thread1")
代替。
equals
比较字符串,==
检查两个字符串是否是同一个对象。
关于java线程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5271278/