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