Java 高并发之设计模式,kafka的原理

本文介绍了Java中利用Future和Callable实现的异步处理,以及生产消费者模式的应用。通过Future,我们可以实现任务的提交与结果获取的解耦。生产消费者模式通过共享内存缓冲区实现多线程间的协作,使用BlockingQueue作为数据交换媒介,提高系统效率。此外,还探讨了Master-Worker模式,展示了如何将任务分配给多个Worker线程并收集结果。
摘要由CSDN通过智能技术生成

1 public class FutureDemo1 {

2

3     public static void main(String[] args) throws InterruptedException, ExecutionException {

4         FutureTask future = new FutureTask(new Callable() {

5             @Override

6             public String call() throws Exception {

7                 return new RealData().costTime();

8             }

9         });

10         ExecutorService service = Executors.newCachedThreadPool();

11         service.submit(future);

12

13         System.out.println(“RealData方法调用完毕”);

14         // 模拟主函数中其他耗时操作

15         doOtherThing();

16         // 获取RealData方法的结果

17         System.out.println(future.get());

18     }

19

20     private static void doOtherThing() throws InterruptedException {

21         Thread.sleep(2000L);

22     }

23 }

24

25 class RealData {

26

27     public String costTime() {

28         try {

29             // 模拟RealData耗时操作

30             Thread.sleep(1000L);

31             return “result”;

32         } catch (InterruptedException e) {

33             e.printStackTrace();

34         }

35         return “exception”;

36     }

37

38 }

通过Future实现

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

1 public class FutureDemo2 {

2

3     public static void main(String[] args) throws InterruptedException, ExecutionException {

4         ExecutorService service = Executors.newCachedThreadPool();

5         Future future = service.submit(new RealData2());

6

7         System.out.println(“RealData2方法调用完毕”);

8         // 模拟主函数中其他耗时操作

9         doOtherThing();

10         // 获取RealData

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值