线程取消原理

线程怎么取消

FutureTask

public class Learn {
    public static final void main(String [] args) {
        FutureTask task  = new FutureTask(new Callable() {

            @Override
            public Object call() throws Exception {
                // TODO Auto-generated method stub
                System.out.println("1234556");
                
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    System.out.println("catch Exception By Interrupt");
                }
                System.out.println("end");
                return null;
            }
            
        });
        new Thread(task).start();
        
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        task.cancel(true);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

支持中断
cancel(true)
这时候直接往线程发中断标志。

不支持中断
cancel(false)
只是设置标志位

可以设置 task.cancel(false);观察2个不同的区别

你可能感兴趣的:(线程取消原理)