当按下一个按钮时,它会在无限循环时卡住

问题描述 投票:-1回答:2

对于我正在尝试的项目,让RFID扫描仪一直按下按钮并在按下停止按钮时重新安装它,但是我已经尝试了一段时间循环但问题似乎是,当我按下按钮代码一切都很完美,它确实循环,但是按下按钮后它不会让我按任何其他东西,因为它卡在while循环中,有没有办法让它保持循环但同时能够阻止它带停止按钮。

  @Override
public void start() {

    while (this.flag) {
        try {
            TerminalFactory factory = TerminalFactory.getDefault();
            List<CardTerminal> terminals = factory.terminals().list();
            System.out.println("Terminals: " + terminals);

            CardTerminal terminal = terminals.get(0);

            System.out.println("Waiting for a card..");
            if (terminal == null) {
                return;
            }
            terminal.waitForCardPresent(0);

            Card card = terminal.connect("T=1");
            System.out.println("Card: " + card);
            System.out.println("Protocol: " + card.getProtocol());
            CardChannel channel = card.getBasicChannel();

            ResponseAPDU response = channel.transmit(new CommandAPDU(new byte[]{(byte) 0xFF, (byte) 0xCA, (byte) 0x00, (byte) 0x00, (byte) 0x00}));
            System.out.println("Response: " + response.toString());
            if (response.getSW1() == 0x63 && response.getSW2() == 0x00) {
                System.out.println("Failed");
            }
            System.out.println("UID: " + bin2hex(response.getData()));

            getUid = bin2hex(response.getData());

            Thread.sleep(1000);
        } catch (CardException e) {
            System.out.println();
            JOptionPane.showMessageDialog(null, "Device Not Connected  " + e.getMessage());
        } catch (InterruptedException ex) {
            Logger.getLogger(CardId.class.getName()).log(Level.SEVERE, null, ex);
        }
}
}

并为我的开始按钮

 t = new CardId();
    t.start();

这是我的停止按钮

 t.flag = false;
java netbeans while-loop rfid
2个回答
0
投票

首先,如果您使用的是Thread,则应该覆盖“run()”方法。不是“start()”方法。您只需要使用“start()”方法来执行线程。否则,它将使用主线程。没有多线程。

第二件事是,如果“this.flag”是您的线程中的实例变量,并且其值由按钮操作动态更改,则该变量应该是volatile。否则它通常在循环中缓存。 (more

建议:请遵循良好的设计模式。 (观测器)


0
投票

按下按钮时不是让你的Thread循环,而是在按下按钮时停止,让循环不断运行。当Thread到达其所需代码体的末尾it does not execute a second time时,即使在调用Thread#start之后。

简而言之,您只需在循环中检查t.flag的值,如果它是false,那么您可以直接睡眠,直到循环的下一次迭代。

© www.soinside.com 2019 - 2024. All rights reserved.