使用多线程实现异步任务

一、springboot中的异步任务

1、使用注解@Async创建一个可异步启动的方法


import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


@Service
public class BeforeCall {


    @SneakyThrows
    @Async
    public void asyncBefore()  {
        Thread.sleep(3000);
        System.out.println("异步方法先调用但是后打印");
    }
}

2、创建一个方便观察的普通方法


import org.springframework.stereotype.Service;

@Service
public class AfterCall {


    public void afcall(){
        System.out.println("普通方法,后调用但是先打印");
    }
}

3、在一个方法中同时调用上面的方法


import com.cai.li.asynctask.service.AfterCall;
import com.cai.li.asynctask.service.BeforeCall;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@ResponseBody
@RequestMapping("/test")
public class DataController {

    @Autowired
    BeforeCall beforeCall;

    @Autowired
    AfterCall afterCall;

    @RequestMapping("/asynctask")
    public void test(){
        beforeCall.asyncBefore();
        afterCall.afcall();
    }


}

4、在springboot启动类上加上注解@EnableAsync


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableAsync
public class AsynctaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsynctaskApplication.class, args);
    }

}

5、访问查看结果

在这里插入图片描述

二、一个线程获取另一个线程中值

1、新建一个类First,类实现Runable接口,在重写的run()方法中获取另一线程中的First类的属性name的值


import lombok.SneakyThrows;

public class First implements Runnable{

    @SneakyThrows
    @Override
    public void run() {
        Thread.sleep(5000);
        Second first = new Second();
        System.out.println("先调用但是后打印");
        System.out.println("新线程"+Thread.currentThread().getName()+"获取的name:"+first.name);

    }
}

2、新建一个类Second,类中的方法Data()负责给属性name赋值


public class Second {

	//属性一定要加static变为静态属性,其他线程取值时才有数据,否则取到的就会是null
    static String name;

    public void Data(String data){
        this.name = data;
        System.out.println("后调用但是后打印");
        System.out.println("线程"+Thread.currentThread().getName()+"中获取到的name:"+name);
    }
}

3、新建一个测试的类


public class AsyncTetst {

    public static void main(String[] args) {
        First first = new First();
        Second second = new Second();
        new Thread(first).start();
        second.Data("Lii");
    }

}

4、运行后的结果

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用线程处理异步任务可以提高程序的并发性和响应性,一般有以下几个步骤: 1. 创建一个线程池,可以使用 Python 内置的 `concurrent.futures.ThreadPoolExecutor` 类来实现。 2. 定义异步任务,可以使用 `asyncio` 库来实现异步任务的定义。 3. 把异步任务提交给线程池执行,可以使用 `submit` 方法来提交任务,并且可以通过 `result` 方法来获取任务的结果。 4. 当所有任务执行完成后,关闭线程池,可以使用 `shutdown` 方法来关闭线程池。 下面是一个使用线程处理异步任务的示例代码: ```python import concurrent.futures import asyncio async def async_task(num): print(f"start async task {num}") await asyncio.sleep(1) print(f"end async task {num}") return num * num async def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor: tasks = [] for i in range(3): task = executor.submit(asyncio.run, async_task(i+1)) tasks.append(task) for task in concurrent.futures.as_completed(tasks): result = task.result() print(f"task result: {result}") asyncio.run(main()) ``` 在这个示例中,我们创建了一个线程池,最大线程数为 3,然后定义了一个异步任务 `async_task`,这个任务会在执行时打印一些信息,然后等待 1 秒钟,最后返回一个数的平方。在 `main` 函数中,我们使用线程池提交了 3 个任务,然后通过 `as_completed` 方法来获取所有任务的结果。最后我们关闭了线程池。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值