zoukankan      html  css  js  c++  java
  • java 同步调用和异步调用


    同步和异步:


    同步和异步通常用来形容一次方法的调用。

    同步方法的调用必须等到该方法返回后才能继续接下来的行为。

    异步方法更像一个消息传递,一旦调用就会立即返回,调用者可以继续接下来的操作,

    而异步方法通常会在另一个线程中执行,不会妨碍调用者的工作。

    示例代码:
    package com.infinitePossibilities.utils;
    import java.util.concurrent.*;
    
    
    public class TbOrYb {
    
        public static void main(String[] args) throws Exception {
    
            TbOrYb tbOrYb = new TbOrYb();
            tbOrYb.tb();
            Thread.sleep(2000);
            System.out.println("
    ");
            tbOrYb.yb();
            Thread.sleep(2000);
            System.out.println("
    ");
            tbOrYb.yb2();
        }
    
        //同步
        public void tb() throws Exception{
    
            TbOrYb tbOrYb = new TbOrYb();
            long start = System.currentTimeMillis();
            tbOrYb.api1("tb");
            tbOrYb.api2("tb");
            long end = System.currentTimeMillis();
            System.out.println("同步用时:"+(start-end));
    
        }
    
        //异步,不要返回结果
        public void yb() throws Exception{
    
            TbOrYb tbOrYb = new TbOrYb();
            long start = System.currentTimeMillis();
    
            new Thread(() -> {
                try {
                    TbOrYb.api1("yb");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
    
            tbOrYb.api2("yb");
            long end = System.currentTimeMillis();
            System.out.println("异步 1 用时:"+(start-end));
        }
    
    
        //异步,要返回结果
        public void yb2() throws Exception {
    
            TbOrYb tbOrYb = new TbOrYb();
            long start = System.currentTimeMillis();
    
    
            Callable<String> callable = new Callable<String>() {
                @Override
                public String call() throws Exception {
                    TbOrYb.api1("yb2");
                    return "111";
                }
            };
            Future <String> future =  threadPoolExecutor.submit(callable);//异步调用执行方法
    
            tbOrYb.api2("yb2");
    
            //这里会阻塞,需要得到返回的结果
            String data = future.get();
    
            long end = System.currentTimeMillis();
            System.out.println("异步 2 用时:"+(start-end)+" 结果:"+data);
            threadPoolExecutor.shutdown();
        }
    
    
    
        public static void api1(String flag) throws Exception {
    
            Thread.sleep(3000);
            System.out.println(flag+" 调用接口 1 完毕!");
        }
    
        public static void  api2(String flag) throws Exception{
    
            Thread.sleep(2000);
            System.out.println(flag+" 调用接口 2 完毕!");
    
        }
    
    
        //自定义线程池
        private ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                                                        1,3,
                                                        60, TimeUnit.SECONDS,
                                                        new ArrayBlockingQueue<>(5),
                                                        Executors.defaultThreadFactory(),
                                                        //自定义拒绝策略
                                                        new MyRejectedExecutionHandler()
                                                        );
    
    }

    运行结果:

    自定义拒绝策略:

    package com.infinitePossibilities.utils.threads.thresdPool_MQ_Impl;
    
    import java.util.Random;
    import java.util.concurrent.RejectedExecutionHandler;
    import java.util.concurrent.ThreadPoolExecutor;
    
    /**
     * 自定义线程池拒绝策略
     */
    public class MyRejectedExecutionHandler implements RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
    //拒绝掉的任务 开启新线程去执行
            new Thread(r,"新启线程"+new Random().nextInt(10)).start();
        }
    }
    
    
    
     
  • 相关阅读:
    微服务架构编码构建
    Keepalived+Nginx 高可用集群
    Nginx 动静分离
    Nginx 负载均衡
    Nginx 反向代理
    Nginx 常用命令
    React.js |Refs转发
    React.js |错误边界
    做一个简约的博客园皮肤
    React.js |Context的作用与用法
  • 原文地址:https://www.cnblogs.com/lifan12589/p/14842323.html
Copyright © 2011-2022 走看看