多线程:切换上下文



我写了一个小示例代码:

public class Button2 implements Runnable{    
    JButton jButton = new JButton();
    static boolean changeContext = false;    
    public Button2(){
        jButton.setText("ButtonTWO");
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeContext = true;
                ((JButton)e.getSource()).setEnabled(false);
            }
        });
    }
    @Override
    public void run() {
        System.out.println("ButtonTWO run...");
        jButton.setEnabled(true);
        while(true){
            if(changeContext)
                break;
        }
        changeContext = false;        
    }
}

当我像这样运行它时:

Button2 threadTWO = new Button2();
Thread thread2;
            try{
                thread2 = new Thread(threadTWO);
            thread2.start();
            thread2.join();
            }catch(Exception ex){
                System.out.println("Ëxception caught");
            }

它永远不会出来,即使在单击按钮后也是如此。

如果我在 while(true) in run method 之后添加一个sysoutThread.sleep(1),它会从 while 循环中出来。可能的原因是什么?

我假设您正在运行EDT的底部。因此,您正在创建按钮(并希望以某种方式将其添加到您的 UI 中),然后启动线程并使 EDT 等待线程死亡(thread2.join()),因此 EDT 无法处理事件并且永远不会调用changeContext = true

添加某些内容使循环结束可能是由于缺少大括号:

这仅在changeContext为 true 时结束循环:

if(changeContext)
   break;

我假设你这样做了:

if(changeContext)
   Thread.sleep(1);
   break;

如果 changeContext 为 true,则上述调用 sleep,然后立即结束循环(break不再在 if 块内。因此,如果您想要一致的行为,请像这样写:

if(changeContext) {
   Thread.sleep(1);
   break;
}

顺便说一句,苹果去年有一个安全问题,基本上有一个类似的来源(双break,没有大括号)。

最新更新