Reputation: 131
I'm new to Java and really can't figure out how some features like interrupting are working. I've read javadocs and previous answers here, so I guess that I should put code in while(!interrupted) cycle and if it recieve interrupted status it should close. I have 2 buttons - start and stop and thread in another class. Thread purpose is to read barcodes - everything works fine, I get right error messages on all exceptions but Thread.currentThread().interrupt(); never works. Same for t.interrupt() - t is instance of thread class. What am i doing wrong?
Buttons:
Thread t = new Serverside();
//start server button
btnStartServer.addActionListener(event ->
{
btnStartServer.setEnabled(false);
btnStopServer.setEnabled(true);
connectButtonPressed = true;
try {
t.start();
}
catch (IllegalThreadStateException e)
{
t.interrupt();
JOptionPane.showMessageDialog(contentPane, "Error, thread already running.");
}
});
//Stop server button
btnStopServer.addActionListener(event ->
{
t.interrupt();
statusMsg.setText("trying to close connection");
});
Class with thread:
class Serverside extends Thread
{
public void run()
{
try {
while(!Serverside.currentThread().interrupted())
{
try {
server = new ServerSocket(Main.sock);
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Порт занят: " + Main.sock);
//
Serverside.currentThread().interrupt();
}
try {
if (connectButtonPressed) {
Main.statusMsg.setText("ожидание подключения на порт " + Main.sock);
Main.client = server.accept();
Main.btnGetPhoto.setEnabled(true);
Main.isconnected = true;
Main.statusMsg.setText("соединение установлено");
//очистка экрана терминала
//Main.client.getOutputStream().write("\u001B[2J".getBytes());
//Main.client.getOutputStream().flush();
}
else
{
JOptionPane.showMessageDialog(null, "Не нажата кнопка connect");
//
Thread.currentThread().interrupt();
}
if (!Main.isconnected)
{
JOptionPane.showMessageDialog(null, "Нет соединения с клиентом");
//
Thread.currentThread().interrupt();
}
while (Main.isconnected) {
BufferedReader br = new BufferedReader(new InputStreamReader(Main.client.getInputStream()));
Main.line = br.readLine();
if (!Serverside.currentThread().interrupted())
{
if (Main.line != null) {
try {
//Заменить строку ниже на динамически выбираемое имя файла
Main.myPicture = ImageIO.read(new File("P:/LM935230105CN.jpg"));
BufferedImage thumbnail = new BufferedImage(612, 512, BufferedImage.TYPE_INT_RGB);
Graphics2D g = thumbnail.createGraphics();
g.drawImage(Main.myPicture, 0, 0, 612, 512, null);
g.dispose();
Main.myIcon = new ImageIcon(thumbnail);
Main.picLabel.setIcon(Main.myIcon);
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Файл не найден!");
}
//Распознавание штрих-кода
Pattern pattern = Pattern.compile("[A-Za-z]{2}[0-9]{9}[A-Za-z]{2}");
Matcher matcher = pattern.matcher(Main.line);
if (matcher.find()) {
Main.barCodeMsg.setText(matcher.group());
Main.barCodeString = (matcher.group());
Main.barCodeStringArray = Main.barCodeString.split("");
final int[] ints = new int[9];
for (int i = 0; i < 9; i++) {
try {
ints[i] = Integer.parseInt(Main.barCodeStringArray[i + 2]);
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
//код проверки контрольной суммы
int checksum = ints[8];
int temp;
temp = 11 - (ints[0] * 8 + ints[1] * 6 + ints[2] * 4 + ints[3] * 2 + ints[4] * 3 + ints[5] * 5 + ints[6] * 9 + ints[7] * 7) % 11;
if (temp == 10) {
temp = 0;
}
if (temp == 11) {
temp = 5;
}
if (temp == checksum) {
Main.statusMsg.setText("штрих-код обнаружен, контрольная сумма совпадает");
} else {
Main.statusMsg.setText("<html><font color='red'>штрих-код обнаружен, контрольная сумма не совпадает</font></html>");
}
} else {
//Строка принята, но штрих-код не распознан
Main.statusMsg.setText("данные не содержат штрих-кода");
barCodeString = "";
}
}
else {
//Строка не содержит данных
Main.picLabel.setIcon(null);
}
}
else {
//blah-blah-blah
JOptionPane.showMessageDialog(null, "Поток прерван.");
break;
}
}
} catch (IOException e) {
//
Serverside.currentThread().interrupt();
JOptionPane.showMessageDialog(null, "Ошибка соединения.");
e.printStackTrace();
} catch (NullPointerException e1) {
JOptionPane.showMessageDialog(null, "Ошибка открытия порта");
//
Serverside.currentThread().interrupt();
e1.printStackTrace();
}
}
}
finally
{
try
{
server.close();
JOptionPane.showMessageDialog(null, "Порт" + sock + " закрыт");
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Ошибка закрытия порта");
e.printStackTrace();
//
Serverside.currentThread().interrupt();
}
}
}
}
Upvotes: 0
Views: 78
Reputation: 16128
I think this could be the point:
while (Main.isconnected) {
In inside you check for interrupted state, but you do not leave the while loop if so. Try adding another check here.
while (Main.isconnected && !Serverside.currentThread().interrupted() {
Also note:
The interrupted status of the thread is cleared by this method.
So I think you should be using isInterrupted()
instead of interrupted()
.
As a sidenote, you could also "clean up" the code a bit by introducing methods being called instead of one long run() method. This helps to keep the overview and debug out flaws in parts of the code. But if this is ok for as is, first "make it run" ... :)
Upvotes: 0