显示使用线程实现异步编程1.0

5 篇文章 0 订阅
0 篇文章 0 订阅

这是一种最简单实现异步的方法之一

public class sync {
    public static void doSomethingA(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-------doSomethingA--------");
    }
    public static void doSomethingB(){
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----------doSomethingB------------");
    }
    
/**
 * 使用异步的方法调用
 * */
 public void nsynThread() throws InterruptedException {
     long start = System.currentTimeMillis();
     Thread thread = new Thread(() ->{
         try {
             doSomethingA();
         } catch (Exception e) {
             e.printStackTrace();
         }
     },"threadA");
     thread.start();
     //执行任务B
     doSomethingB();
     //3、同步等待线程A运行之后的结果
      thread.join();
     System.out.println(System.currentTimeMillis()-start);

 }
 /**
  * 开启线程进行异步执行的方式,并重写run方法
  * */
 public void overirideThread() throws InterruptedException {
     long start = System.currentTimeMillis();
     Thread thread = new Thread("threadA"){
         @Override
         public void run() {
             try {
                 doSomethingA();
             } catch (Exception e) {
                 e.printStackTrace();
             }

         }

     };
     thread.start();
     //2.执行任务B
     doSomethingB();
     //3.同步等待线程A运行结果
     thread.join();
     System.out.println(System.currentTimeMillis()-start);
 }
    public static void main(String[] args) throws InterruptedException {
        sync sync = new sync();
        sync.overirideThread();
    }
}

如果是同步进行的那么执行时间大概4S左右;但用异步实现的话就是那就是2S左右;
第一种是方式是实现java.lang.Runnable接口的run方式;
第二种开启了线程进行异步执行的方式是实现Thread类。并重写run方法;

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值