How do you kill a Thread in Java?

前端 未结 16 2100
天命终不由人
天命终不由人 2020-11-21 05:54

How do you kill a java.lang.Thread in Java?

16条回答
  •  青春惊慌失措
    2020-11-21 06:41

    Thread.stop is deprecated so how do we stop a thread in java ?

    Always use interrupt method and future to request cancellation

    1. When the task responds to interrupt signal, for example, blocking queue take method.
    Callable < String > callable = new Callable < String > () {
        @Override
        public String call() throws Exception {
            String result = "";
            try {
                //assume below take method is blocked as no work is produced.
                result = queue.take();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return result;
        }
    };
    Future future = executor.submit(callable);
    try {
        String result = future.get(5, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        logger.error("Thread timedout!");
        return "";
    } finally {
        //this will call interrupt on queue which will abort the operation.
        //if it completes before time out, it has no side effects
        future.cancel(true);
    }
    
    
    1. When the task does not respond to interrupt signal.Suppose the task performs socket I/O which does not respond to interrupt signal and thus using above approach will not abort the task, future would time out but the cancel in finally block will have no effect, thread will keep on listening to socket. We can close the socket or call close method on connection if implemented by pool.
    public interface CustomCallable < T > extends Callable < T > {
        void cancel();
        RunnableFuture < T > newTask();
    }
    
    public class CustomExecutorPool extends ThreadPoolExecutor {
        protected < T > RunnableFuture < T > newTaskFor(Callable < T > callable) {
            if (callable instanceof CancellableTask)
                return ((CancellableTask < T > ) callable).newTask();
            else
                return super.newTaskFor(callable);
        }
    }
    
    public abstract class UnblockingIOTask < T > implements CustomCallable < T > {
        public synchronized void cancel() {
            try {
                obj.close();
            } catch (IOException e) {
                logger.error("io exception", e);
            }
        }
    
        public RunnableFuture < T > newTask() {
            return new FutureTask < T > (this) {
                public boolean cancel(boolean mayInterruptIfRunning) {
                    try {
                        this.cancel();
                    } finally {
                        return super.cancel(mayInterruptIfRunning);
                    }
                }
    
            };
        }
    }
    

提交回复
热议问题