How interrupt/stop a thread in Java?

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

    Simply return; from your while and the thread will die, no need to call stop() or interrupt(). If you want to do it externally then use this pattern and call requestStop().

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

提交回复
热议问题