设为首页 加入收藏

TOP

Java高并发之设计模式(二)
2018-07-13 06:07:18 】 浏览:378
Tags:Java 并发 设计模式
时操作
            Thread.sleep(1000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }


}


通过Future实现


与上述FutureTask不同的是, RealData需要实现Callable接口.


public class FutureDemo2 {


    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newCachedThreadPool();
        Future<String> future = service.submit(new RealData2());


        System.out.println("RealData2方法调用完毕");
        // 模拟主函数中其他耗时操作
        doOtherThing();
        // 获取RealData2方法的结果
        System.out.println(future.get());
    }


    private static void doOtherThing() throws InterruptedException {
        Thread.sleep(2000L);
    }
}


class RealData2 implements Callable<String>{


    public String costTime() {
        try {
            // 模拟RealData耗时操作
            Thread.sleep(1000L);
            return "result";
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "exception";
    }


    @Override
    public String call() throws Exception {
        return costTime();
    }
}


另外Future本身还提供了一些额外的简单控制功能, 其API如下


// 取消任务
    boolean cancel(boolean mayInterruptIfRunning);
    // 是否已经取消
    boolean isCancelled();
    // 是否已经完成
    boolean isDone();
    // 取得返回对象
    V get() throws InterruptedException, ExecutionException;
    // 取得返回对象, 并可以设置超时时间
    V get(long timeout, TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException;


生产者-消费者模式是一个经典的多线程设计模式. 它为多线程间的协作提供了良好的解决方案。


在生产者-消费者模式中,通常由两类线程,即若干个生产者线程和若干个消费者线程。


生产者线程负责提交用户请求,消费者线程则负责具体处理生产者提交的任务。


生产者和消费者之间则通过共享内存缓冲区进行通信, 其结构图如下



PCData为我们需要处理的元数据模型, 生产者构建PCData, 并放入缓冲队列.


消费者从缓冲队列中获取数据, 并执行计算.


生产者核心代码


while(isRunning) {
            Thread.sleep(r.nextInt(SLEEP_TIME));
            data = new PCData(count.incrementAndGet);
            // 构造任务数据
            System.out.println(data + " is put into queue");
            if (!queue.offer(data, 2, TimeUnit.SECONDS)) {
                // 将数据放入队列缓冲区中
                System.out.println("faild to put data : " + data);
            }
        }


消费者核心代码


while (true) {
            PCData data = queue.take();
      &nbs

首页 上一页 1 2 3 4 5 下一页 尾页 2/5/5
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Go语言实现struct转map 下一篇Excel支持使用JavaScript自定义函..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目