首页 > 编程语言 > 详细

JAVA使用异步线程

时间:2021-06-01 00:45:53      阅读:16      评论:0      收藏:0      [点我收藏+]

JAVA使用异步线程

使用线程池

ExecutorService executorService = Executors.newCachedThreadPool();
		//线程一
        executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                for (int i = 0; i < 100; i++) {
                    Thread.sleep(1000);
                    System.out.println("Thread1"+i);
                }
                return null;
            }
        });
        //线程二
        executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                for (int i = 0; i < 100; i++) {
                    Thread.sleep(1000);
                    System.out.println("Thread2"+i);
                }
                return null;
            }
        });
    }

使用spring注解

@EnableDiscoveryClient
@SpringBootApplication
@EnableAsync//启动类添加注解开启异步
public class UserApplication {

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

}

@Async可以加在类上也可以加在方法上,加在类上对所有方法生效,加在方法上对方法生效(需被spring管理)

@Service
public class AsyncServiceImpl {
    @Async
    public void asyncMethod(String str) throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            Thread.sleep(1000);
            System.out.println(str+i);
        }
    }
}

效果

@RestController
public class AsyncController {
    @Autowired
    AsyncServiceImpl asyncService;
    @PostMapping("/asyncTest")
    public void asyncTest(){
        try {
            asyncService.asyncMethod("线程一");
            asyncService.asyncMethod("线程二");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return;
    }
}

JAVA使用异步线程

原文:https://www.cnblogs.com/xzh-hash/p/14833839.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!