中断可运行线程的问题

时间:2019-12-30 10:46:49

标签: java multithreading interrupt

我想用JFrame窗口运行一个类,等待它关闭,然后再启动另一个类,等等。(这应该是一个简单的登录窗口,随后会打开一个聊天窗口。)

此时,我正在努力中断正在运行登录窗口的线程。由于某种原因,无论我尝试什么,它都不会中断。这是基本代码:

public class Main {

public static void main(String[] args) throws InterruptedException {
    Account acc=new Account();  //create new account
    Thread t=new Thread(acc);   //put it in a thread
    a1.run();                   //start the thread
    while(t.isAlive()) {
        if(acc.success) {        //successful login
            t.interrupt();
        }
    }
    t.join();                   //wait for t to die
    System.out.println("Hello");
}

有关Account类的详细信息并不重要。它实现可运行,完成所有登录工作,如果成功,它将布尔成功更改为true,这将触发main中的中断。程序还应等待t被打断,然后打印“ Hello”,但不会。运行代码时,始终会立即打印出“ Hello”。

编辑:

public class Account extends JFrame implements Runnable {
JFrame window;
boolean success = false;

public Account() {
    super("Login");
}

@Override
public void run() {
    JButton login = new JButton("Login");
    window = new JFrame();
    window.setSize(500, 120);
    window.setLayout(new BorderLayout());

    window.add(login, BorderLayout.SOUTH);
    window.setVisible(true);
    login.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            checkAndFinish();
        }

    });

}

protected void checkAndFinish() {// no matter how, after checking the login the thread is supposed to close
    // Check if the login is correct, missing here for the sake of simplicity
    this.success = true;
    Thread.currentThread().interrupt();
}

}

这是帐户中的代码。它应该做的就是

if button pressed
kill this Thread

但它不像Thread.currentThread()。interrupt();

那样简单

0 个答案:

没有答案