JAVA使用异步线程


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;
    }
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM