sudojdoe sudojdoe - 3 years ago 212
Java Question

Java Thread active after interruptting

I am Creating a Thread for this class from the main function but even after it is interrupted using Thread.currentThread().interrupt() output still contains the line Still Here.

public class WriteToServer extends Thread {

private DataOutputStream writeMessage;

private String clientName;

public WriteToServer(Socket socket, String clientName) {
try {
this.writeMessage = new DataOutputStream(socket.getOutputStream());
this.clientName = clientName;
} catch(Exception e) {
System.err.println(e);

Thread.currentThread().interrupt();
}
}

public void run() {
try {
Scanner scanner = new Scanner(System.in);
String message = scanner.nextLine();

while (!message.equalsIgnoreCase("quit")) {
writeMessage.writeUTF(clientName + ":" + message);
message = scanner.nextLine();
}

writeMessage.writeUTF(message);
writeMessage.close();

Thread.currentThread().interrupt();

System.out.println("Still Here");
} catch(Exception e) {
System.err.println(e);

Thread.currentThread().interrupt();
}
}
}


I am New To Java And I want to improve Any Suggestions?

Answer Source

There is no legal way to immediately stop thread execution in Java. Calling Thread#interrupt() just sets the interrupted flag on thread to true. It is your responsibility as a programmer to check for interrupted flag inside your code and properly shutdown thread activities.

In your example you can just write a return statement that will finish execution of run() method.

For more information check on something like next post: https://www.javaworld.com/article/2077138/java-concurrency/introduction-to-java-threads.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download