Issue
For my project i am trying to, get the RFID scanner to run all the time by pressing a button and reasing it when stop button is pressed, however i have tried to in a while loop but the problem seems like, when i press the button code everything works perfectly and it does go in a loop however after the button is pressed it doesnt let me press anything else because it stuck in the while loop, is there a way to keep it in a loop but in same time able to stop it with stop button.
@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);
}
}
}
and for my start button
t = new CardId();
t.start();
and this is my stop button
t.flag = false;
Solution
First thing is, if you are using a Thread, you should override the "run()" method. NOT the "start()" method. You need to use the "start()" method only to execute the thread. Otherwise, it will use the main thread. No multithreading.
Second thing is, if the "this.flag" is an instance variable in your thread, and its value is dynamically changed by button actions, that variable should be volatile. Otherwise it is normally cached within the loop. (more)
Suggestion: Please follow a good design pattern. (Observer)
Answered By - Amila Jayawardhana
Answer Checked By - Terry (JavaFixing Volunteer)