简体   繁体   中英

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?

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

As suggested, return will just finish the execution of run() . If you want to check first if the thread was interrupted (by another thread), you can do:

if (Thread.currentThread().isInterrupted()) {
     return;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM