无法使Thread.interrupt工作

时间:2018-01-10 00:48:35

标签: java multithreading swing interrupt-handling

我有一个程序执行一些文件I / O然后睡眠几秒钟,检查文件是否已经改变,然后睡觉,如果它们相同。如果它们已更改,它将执行相同的文件I / O然后重新进入休眠状态。我想实现一个按键,如果按下它将唤醒该线程,但我无法让线程处理InterruptedException。我的(简化)代码在这里:

import java.awt.Color;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class StackOverFlowExample extends JFrame{

    private class MyDispatcher implements KeyEventDispatcher {
        boolean keyEventDone = false;

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if(e.getID() == KeyEvent.KEY_PRESSED){
                if((e.getKeyCode() == 80 && e.getModifiers() == 11) && !keyEventDone){
                    System.out.println("interrupting");
                    interrupt();
                }
            }
            if (e.getID() == KeyEvent.KEY_RELEASED) {
                if(e.getKeyCode() == 80){
                    keyEventDone = false;
                }
            }
            return true;
        }

    }

public void interrupt(){
    System.out.println("recieved interrupt");
    Thread.currentThread().interrupt();
}

public static void main(String[] args){
    String fileName = "file Name";
    String oldFileName = "oldFileName";
    JFrame frame = new StackOverFlowExample();
    frame.setUndecorated(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
    frame.setSize(217, 104);

    do{
        if(!fileName.equals(oldFileName)){

        }else{
            try {
                System.out.println("Same file");
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                System.out.println("continuing");
                if(Thread.currentThread().isInterrupted()){
                    System.out.println("continuing");
                    continue;
                }
                e.printStackTrace();
            }
        }
        oldFileName = fileName;
    }while(true);

}
public StackOverFlowExample(){
    super("");
    JPanel pane = new JPanel();
    pane.setBackground(Color.LIGHT_GRAY);
    setContentPane(pane);
    KeyboardFocusManager manager = 
    KeyboardFocusManager.getCurrentKeyboardFocusManager();
manager.addKeyEventDispatcher(new MyDispatcher());
}

}

班上还有其他东西,但没有一个与线程或任何东西有关。另外,我知道检查文件名并不是最好的方法,但在我的应用程序中,如果文件不同,文件名将始终不同,因为文件名是根据时间生成的。

当我按下" ctrl + shift + alt + p"唤醒它打印出来的线程"打断"来自MyDispatcher类和"收到中断"从主类的中断方法,但没有别的和线程只是保持睡眠

我看到的所有中断睡眠线程的例子都有不在主类中的线程。这是我的工作不起作用的原因吗?

1 个答案:

答案 0 :(得分:1)

同样,您正在中断错误的线程,并希望传递正确的线程。例如,接受您的代码:

import java.awt.Color;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

@SuppressWarnings("serial")
public class StackOverFlowExample extends JFrame {
    static String oldFileName = "oldFileName";
    private Thread runningThread;

    private class MyDispatcher implements KeyEventDispatcher {
        boolean keyEventDone = false;

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                if ((e.getKeyCode() == 80 && e.getModifiers() == 11) && !keyEventDone) {
                    System.out.println("interrupting");
                    interrupt();
                }
            }
            if (e.getID() == KeyEvent.KEY_RELEASED) {
                if (e.getKeyCode() == 80) {
                    keyEventDone = false;
                }
            }
            return true;
        }

    }

    // pass in the correct thread to interrupt
    public void setRunningThread(Thread runningThread) {
        this.runningThread = runningThread;
    }

    public void interrupt() {
        System.out.println("recieved interrupt");
        // !! Thread.currentThread().interrupt();
        runningThread.interrupt();
        System.out.println("interrupt Thread id: " + Thread.currentThread().getId());
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            String fileName = "file Name";
            StackOverFlowExample frame = new StackOverFlowExample();
            frame.setUndecorated(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setVisible(true);
            frame.setSize(217, 104);

            Thread thread = new Thread(() -> {
                do {
                    if (!fileName.equals(oldFileName)) {

                    } else {
                        try {
                            System.out.println("do-while Thread id: " + Thread.currentThread().getId());

                            System.out.println("Same file");
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            System.out.println("continuing");
                            if (Thread.currentThread().isInterrupted()) {
                                System.out.println("continuing");
                                continue;
                            }
                            e.printStackTrace();
                        }
                    }
                    oldFileName = fileName;
                } while (true);
            });

            // pass in the thread
            frame.setRunningThread(thread);
            thread.start(); // start it running
        });
    }

    public StackOverFlowExample() {
        super("");
        JPanel pane = new JPanel();
        pane.setBackground(Color.LIGHT_GRAY);
        setContentPane(pane);
        KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
        manager.addKeyEventDispatcher(new MyDispatcher());
    }

}

你知道,也许是一种更简单的方法来做你正在尝试做的事情:

  • 创建一个每x秒重复一次的Swing Timer(在本例中我们将使用10秒)
  • 在计时器内部启动一个新的Thread,如果我们需要它与GUI更直接地交互,可能是SwingWorker,它会检查文件情况并在需要时进行文件I / O.
  • 给定时器初始延迟0,因此它立即启动或重新启动
  • 使用键绑定而不是烦躁的KeyListener
  • 在我们的绑定触发的Action中,只需在Swing Timer上调用restart(),它会立即重新启动其动作,因为初始延迟为0,然后重新启动10秒等待。

类似的东西:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class StackOverflowExample2 extends JPanel {
    // 10 seconds between tasks
    private static final int TIMER_DELAY = 10 * 1000;
    int keyCode = KeyEvent.VK_P;
    int modifiers = InputEvent.SHIFT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK
            | InputEvent.ALT_DOWN_MASK;
    private KeyStroke shftCtrlAltP = KeyStroke.getKeyStroke(keyCode, modifiers);
    private int condition = WHEN_IN_FOCUSED_WINDOW;
    private InputMap inputMap = getInputMap(condition);
    private ActionMap actionMap = getActionMap();
    private Timer myTimer = new Timer(TIMER_DELAY, new TimerListener());

    public StackOverflowExample2() {
        setPreferredSize(new Dimension(400, 300));

        // create key binding
        inputMap.put(shftCtrlAltP, shftCtrlAltP.toString());
        actionMap.put(shftCtrlAltP.toString(), new MyAction());
        // myWorker.execute();
        myTimer.setInitialDelay(0);
        myTimer.start();
    }

    private class MyAction extends AbstractAction {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Key pressed");
            myTimer.restart(); // simply re-start the timer
        }
    }

    private class TimerListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // launch SwingWorker or other thread to check if files have changed
            // and if so do file I/O
            System.out.println("Timer running");
        }
    }

    private static void createAndShowGui() {
        StackOverflowExample2 mainPanel = new StackOverflowExample2();

        JFrame frame = new JFrame("StackOverflowExample2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

此外,您的代码和程序设计目前要求轮询文件或多个文件的状态,然后在更改时执行某些操作。更有效的替代方法是根本不进行轮询,而是使用自Java 7以来的核心Java API的Java NIO WatchService API部分。