How interrupt/stop a thread in Java?

后端 未结 8 1775
失恋的感觉
失恋的感觉 2020-12-05 07:48

I\'m trying to stop a thread but I can\'t do that :

public class Middleware {

public void read() {
    try {
        socket = new Socket(\"192.168.1.8\", 20         


        
相关标签:
8条回答
  • 2020-12-05 08:47

    if you want to interrupt a running thread, then you need to have access to the thread object.

    thread = new Thread(scan);
    thread.start();
    

    then say

    thread.interrupt();
    

    this will interrupt the running thread.

    0 讨论(0)
  • 2020-12-05 08:50

    Completely agree with Jim.. Just to add If your thread is blocked inside the try block for instance reading on a datastream etc then interrupt the thread as well or close the stream. In both cases the thread should be wakened up again and it will then be able to see the change in the value of "stop" boolean and die naturally by falling out of the run method. At least this is what I did to kill my threads in the shutdown thread for my server.

    0 讨论(0)
提交回复
热议问题