How interrupt/stop a thread in Java?

后端 未结 8 1780
失恋的感觉
失恋的感觉 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:44

    The usual way to stop a thread is to have a volatile flag and then check that in the run method. i.e.

    class Scan extends Thread {
        volatile stop = false;
        public void run() {
    
            while (!stop) {
                try {
                // my code goes here
    
                } catch (IOException ex) {
                    thread.currentThread().interrupt();
                }
            }
        }
    
        public void stop(){
            stop = true;
        }
    }
    

    You can then call scan.stop().

提交回复
热议问题