How interrupt/stop a thread in Java?

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

    There's really no reason you need to use a volatile flag. Instead, just query the thread for its state with isInterrupted(). Also, why are you wrapping your Scan thread object in another thread object? That seems completely unnecessary to me.

    Here' what you should be doing

    public class Middleware {
        private Scan scan;
    
        public void read() {
            try {
                // do stuff
    
                scan = new Scan();
                scan.start();
            } catch (UnknownHostException ex) {
                // handle exception
            } catch (IOException ex) {
                // handle exception
            }
        }
    
        private class Scan extends Thread {
    
            @Override
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        // my code goes here
                    } catch (IOException ex) {
                        Thread.currentThread().interrupt();
                    }
                }
            }
        }
    
        public void stop() {
            if(scan != null){
                scan.interrupt();
            }
        }
    }
    

    Here's an example. Also, I wouldn't recommend extending Thread.

提交回复
热议问题