采用newTaskFor来封装非标准的取消

package canceltask;

import java.util.concurrent.Callable;
import java.util.concurrent.RunnableFuture;

/**
 * 接口:封装一个取消任务
 * */
public interface CancellableTask<T> extends Callable {
    // 取消
    void cancel();
    // 新任务,返回RunnableFuture
    RunnableFuture<T> newTask();
}
package canceltask;

import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;

/**
 *  实现取消任务的抽象类
 * */
public abstract class SocketUsingTask<T> implements CancellableTask {
    private Socket socket;

    protected synchronized void setSocket (Socket s) {
        this.socket = s;
    }

    // 实现取消任务的方法,socket可通过关闭底层套接字,实现中断
    public synchronized void cancel () {
        if (socket == null) {
            try {
                // 关闭套接字,使执行write,read方法而被阻塞的线程抛出SocketException
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 新建任务
    @Override
    public RunnableFuture newTask() {
        // 推荐使用:本类中重写方法,任何在return时(或其他情况下)调用重写的方法,很巧妙
        return new FutureTask<T>(this) {
            // 重写FutureTask中的cancel方法
            public boolean cancel(boolean mayInterruptIfRunning) {
                try {
                    // 类名.this:类的对象
                    // 1.调用cancel方法,关闭套接字连接,这时cancel方法抛出异常没事。
                    SocketUsingTask.this.cancel();
                } finally {
                    // 2.使用FutureTask取消任务
                    return super.cancel(mayInterruptIfRunning);
                }
            }
        };
    }
}

 

package canceltask;

import java.util.concurrent.*;

public class CancellingExecutor extends ThreadPoolExecutor {
    public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    }

    public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    }

    public CancellingExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    }



    // 创建任务
    protected<T> RunnableFuture<T> newTaskFor (Callable<T> callable) {
        if (callable instanceof CancellableTask) {
            return ((CancellableTask) callable).newTask();
        } else {
            return super.newTaskFor(callable);
        }
    }

    // 模拟测试方法
    public void test () throws InterruptedException {
        RunnableFuture<Integer> tt = newTaskFor(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                for (int i = 0; i < 200000; i++) {
                    System.out.println(i+ ", ");
                }
                return 1;
            }
        });

        Thread.sleep(1);

        tt.cancel(true);
    }


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值