Java 定制并发类 详解

可以基于 Java提供类和接口来实现定制并发工具

定制 ThreadPoolExecutor类

public class SleepTwoSecondsTask implements Callable<String> {
    @Override
    public String call() throws Exception {
        TimeUnit. SECONDS .sleep( 2 );
        return new Date().toString();
    }
}

public class MyExecutor extends ThreadPoolExecutor {
    private ConcurrentHashMap<String, Date> startTimes ;
    public MyExecutor( int corePoolSize, int maximunPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super (corePoolSize, maximunPoolSize, keepAliveTime, unit, workQueue);
        startTimes = new ConcurrentHashMap<>();
    }
    @Override
    public void shutdown() {
        System. out .printf( "MyExecutor: Going to shutdown. \n " );
        System. out .printf( "MyExecutor: Executed tasks:%d \n " , getCompletedTaskCount());
        System. out .printf( "MyExecutor: Running tasks:%d \n " , getActiveCount());
        System. out .printf( "MyExecutor: Pending tasks:5d \n " , getQueue().size());
        super .shutdown();
    }
    @Override
    public List<Runnable> shutdownNow() {
        System. out .printf( "MyExecutor: Going to immediately shutdown. \n " );
        System. out .printf( "MyExecutor: Executed tasks:%d \n " , getCompletedTaskCount());
        System. out .printf( "MyExecutor: Running tasks:%d \n " , getActiveCount());
        System. out .printf( "MyExecutor: Pending tasks:5d \n " , getQueue().size());
        return super .shutdownNow();
    }
    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        System. out .printf( "MyExecutor: A task is beginning: %s : %s \n " , t.getName(), r.hashCode());
        startTimes .put(String. valueOf (r.hashCode()), new Date());
    }
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        Future<?> result = (Future<?>) r;
        try {
            System. out .printf( "******************************* \n " );
            System. out .printf( "MyExecutor: A task is finishing. \n " );
            System. out .printf( "MyExecutor: Result: %s \n " , result.get());
            Date startDate = startTimes .remove(String. valueOf (r.hashCode()));
            Date finishDate = new Date();
            long diff = finishDate.getTime() - startDate.getTime();
            System. out .printf( "MyExecutor: Duration: %d \n " , diff);
            System. out .printf( "******************************* \n " );
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        MyExecutor myExecutor = new MyExecutor( 2 , 4 , 1000 , TimeUnit. MILLISECONDS , new LinkedBlockingDeque<>());
        List<Future<String>> results = new ArrayList<>();
        for ( int i = 0 ; i < 10 ; i++) {
            SleepTwoSecondsTask task = new SleepTwoSecondsTask();
            Future<String> result = myExecutor.submit(task);
            results.add(result);
        }
        try {
            for ( int i = 0 ; i < 5 ; i++) {
                String result = results.get(i).get();
                System. out .printf( "Main: Result for Task %d : %s \n " , i, result);
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        myExecutor.shutdown();
        try {
            for ( int i = 5 ; i < 10 ; i++) {
                String result = results.get(i).get();
                System. out .printf( "Main: Result for Task %d : %s \n " , i, result);
            }
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        try {
            myExecutor.awaitTermination( 1 , TimeUnit. DAYS );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System. out .printf( "Main: End of the program. \n " );
    }
}


基于优先级的 Executor类

public class MyPriorityTask implements Runnable, Comparable<MyPriorityTask> {
    private int priority ;
    private String name ;
    public MyPriorityTask( int priority, String name) {
        this . priority = priority;
        this . name = name;
    }
    public int getPriority() {
        return priority ;
    }
    @Override
    public int compareTo(MyPriorityTask o) {
        if ( this . priority < o.getPriority()) {
            return 1 ;
        } else if ( this . priority > o.getPriority()) {
            return - 1 ;
        }
        return 0 ;
    }
    @Override
    public void run() {
        System. out .printf( "MyPriorityTask: %s Priority : %d \n " , name , priority );
        try {
            TimeUnit. SECONDS .sleep( 2 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor( 2 , 2 , 1 ,
                TimeUnit. SECONDS , new PriorityBlockingQueue<Runnable>());
        for ( int i = 0 ; i < 4 ; i++) {
            MyPriorityTask task = new MyPriorityTask(i, "Task " + i);
            executor.execute(task);
        }
        try {
            TimeUnit. SECONDS .sleep( 1 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for ( int i = 4 ; i < 8 ; i++) {
            MyPriorityTask task = new MyPriorityTask(i, "Task " + i);
            executor.execute(task);
        }
        executor.shutdown();
        try {
            executor.awaitTermination( 1 , TimeUnit. DAYS );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System. out .printf( "Main: End of the program. \n " );
    }
}

ThreadFactory 接口生成定制线程

public class MyTask implements Runnable {
    @Override
    public void run() {
        try {
            TimeUnit. SECONDS .sleep( 2 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class MyThread extends Thread {
    private Date creationDate ;
    private Date startDate ;
    private Date finishDate ;
    public MyThread(Runnable target, String name) {
        super (target, name);
        setCreationDate();
    }
    @Override
    public void run() {
        setStartDate();
        super .run();
        setFinishDate();
    }
    public void setCreationDate() {
        creationDate = new Date();
    }
    public void setStartDate() {
        startDate = new Date();
    }
    public void setFinishDate() {
        finishDate = new Date();
    }
    public long getExecutionTime() {
        return finishDate .getTime() - startDate .getTime();
    }
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        buffer.append(getName()).append( ": " )
                .append( " Creation date: " ).append( creationDate )
                .append( " : Running time: " ).append(getExecutionTime())
                .append( " Milliseconds." );
        return buffer.toString();
    }
}

public class MyThreadFactory implements ThreadFactory {
    private int counter ;
    private String prefix ;
    public MyThreadFactory(String prefix) {
        this . prefix = prefix;
        counter = 1 ;
    }
    @Override
    public Thread newThread(Runnable r) {
        MyThread myThread = new MyThread(r, prefix + "-" + counter );
        counter ++;
        return myThread;
    }
    public static void main(String[] args) throws InterruptedException {
        MyThreadFactory myFactory = new MyThreadFactory( "MyThreadFactory" );
        MyTask task = new MyTask();
        Thread thread = myFactory.newThread(task);

        thread.start();
        thread.join();
        System. out .printf( "Main: Thread information. \n " );
        System. out .printf( "%s \n " , thread);
        System. out .printf( "Main: End of example. \n " );
    }
}

定制运行在定时线程池中的任务

public class Task implements Runnable {
    @Override
    public void run() {
        System. out .printf( "Task: Begin. \n " );
        try {
            TimeUnit. SECONDS .sleep( 2 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System. out .printf( "Task: End. \n " );
    }
}

public class MyScheduledTask< V > extends FutureTask< V > implements RunnableScheduledFuture< V > {
    private RunnableScheduledFuture< V > task ;
    private ScheduledThreadPoolExecutor executor ;
    private long period ;
    private long startDate ;
    public MyScheduledTask(Runnable runnable, V result, RunnableScheduledFuture< V > task , ScheduledThreadPoolExecutor executor) {
        super (runnable, result);
        this . task = task;
        this . executor = executor;
    }
    @Override
    public long getDelay(TimeUnit unit) {
        if (!isPeriodic()) {
            return task .getDelay(unit);
        } else {
            if ( startDate == 0 ) {
                return task .getDelay(unit);
            } else {
                Date now = new Date();
                long delay = startDate - now.getTime();
                return unit.convert(delay, TimeUnit. MILLISECONDS );
            }
        }
    }
    @Override
    public int compareTo(Delayed o) {
        return task .compareTo(o);
    }
    @Override
    public boolean isPeriodic() {
        return task .isPeriodic();
    }
    @Override
    public void run() {
        if (isPeriodic() && ! executor .isShutdown()) {
            Date now = new Date();
            startDate = now.getTime() + period ;
            executor .getQueue().add( this );
        }
        System. out .printf( "Pre-MyScheduledTask: %s \n " , new Date());
        System. out .printf( "MyScheduledTask: Is Periodic: %s \n " , isPeriodic());
        super .runAndReset();
        System. out .printf( "Post-MyScheduledTask: %s \n " , new Date());
    }
    public void setPeriod( long period) {
        this . period = period;
    }
}

public class MyScheduledThreadPoolExecutor extends ScheduledThreadPoolExecutor {
    public MyScheduledThreadPoolExecutor( int corePoolSize) {
        super (corePoolSize);
    }
    @Override
    protected < V > RunnableScheduledFuture< V > decorateTask(Runnable runnable, RunnableScheduledFuture< V > task) {
        return new MyScheduledTask<>(runnable, null , task, this );
    }
    @Override
    public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) {
        ScheduledFuture<?> task = super .scheduleAtFixedRate(command, initialDelay, period, unit);
        MyScheduledTask<?> myTask = (MyScheduledTask<?>) task;
        myTask.setPeriod(TimeUnit. MILLISECONDS .convert(period, unit));
        return myTask;
    }
    public static void main(String[] args) throws InterruptedException {
        MyScheduledThreadPoolExecutor executor = new MyScheduledThreadPoolExecutor( 2 );
        Task task = new Task();
        System. out .printf( "Main: %s \n " , new Date());
        executor.schedule(task, 1 , TimeUnit. SECONDS );
        TimeUnit. SECONDS .sleep( 3 );
        task = new Task();
        System. out .printf( "Main: %s \n " , new Date());
        executor.scheduleAtFixedRate(task, 1 , 3 , TimeUnit. SECONDS );
        TimeUnit. SECONDS .sleep( 10 );
        executor.shutdown();
        executor.awaitTermination( 1 , TimeUnit. DAYS );
        System. out .printf( "Main: End of the program. \n " );
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值