[thread](https://ithelp.ithome.com.tw/articles/10201500) [DeadLock](https://www.liaoxuefeng.com/wiki/1252599548343744/1306580888846370) [CompletableFuture](https://blog.csdn.net/zsx_xiaoxin/article/details/123898171) [Thread](https://popcornylu.gitbooks.io/java_multithread/content/async/cfuture.html) 應用場景: - 並行執行任務: 當某些任務可以獨立執行時,可以使用線程實現並行處理,提高程序的執行效率。 - 非阻塞執行: 在需要執行一些可能耗時的操作時,可以將這些操作放在獨立的線程中,從而不阻塞主程序的執行。 - 定時任務: 使用線程可以實現定時執行的任務,例如定時更新某些數據、定時檢查某些條件等。 - 多用戶請求處理: 在服務器應用中,每個用戶的請求可以在獨立的線程中處理,從而實現多用戶同時訪問。 在 Spring Boot 中,雖然你可能沒有直接看到 Thread 類的字眼,但是 Spring Boot 提供了一個豐富的多線程支持。 以下是在 Spring Boot 中使用多線程的一些常見方式: - 使用 @Async 標記方法: 通過在方法上添加@Async標記,該方法將在一個單獨的線程中執行,可以實現非阻塞的異步執行。 ```javascript= @Service public class MyService { @Async public void asyncMethod() { // 非阻塞的異步操作 } } ``` - 使用 ThreadPoolTaskExecutor: Spring 提供了 ThreadPoolTaskExecutor 來管理線程池,可以配置並發線程的數量等。 ```javascript= @Configuration @EnableAsync public class AsyncConfig { @Bean public ThreadPoolTaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(5); executor.setMaxPoolSize(10); executor.setQueueCapacity(25); return executor; } } ``` - 使用 @Scheduled 標記定時任務: 可以使用 @Scheduled 標記方法,該方法將在固定的時間間隔內定期執行。 ```javascript= @Service public class MyScheduledService { @Scheduled(fixedRate = 5000) public void scheduledMethod() { // 定時執行的任務 } } ``` - 多用戶請求處理 - Start the App,加@EnableAsync ```javascript= @SpringBootApplication @EnableAsync public class EcommerceApplication { public static void main(String[] args) { SpringApplication.run(EcommerceApplication.class, args); } } ``` ```javascript= @Service public class OrderService { @Async public CompletableFuture<String> processOrder(Order order) { // 處理訂單的邏輯,例如確認訂單、庫存扣減等 // 模擬耗時操作 try { Thread.sleep(5000); // 5秒 } catch (InterruptedException e) { e.printStackTrace(); } return CompletableFuture.completedFuture("Order processed: " + order.getId()); } } ``` ```javascript= @RestController @RequestMapping("/api/orders") public class OrderController { private final OrderService orderService; public OrderController(OrderService orderService) { this.orderService = orderService; } @PostMapping public ResponseEntity<String> placeOrder(@RequestBody Order order) { CompletableFuture<String> result = orderService.processOrder(order); return ResponseEntity.accepted().body("Order processing started. Result will be available shortly."); } } ``` --- ```javascript= import java.util.concurrent.atomic.AtomicInteger; public class Counter2 { private static int counter = 0; private static AtomicInteger atomicCounter = new AtomicInteger(0); public static void main(String[] args) throws InterruptedException { Thread t1 = new Thread(() -> { System.out.println("t1 starts."); for (int i = 0; i < 1000000; i++) { counter++; } System.out.println("t1 ends."); }); t1.start(); Thread t2 = new Thread(() -> { System.out.println("t2 starts."); for (int i = 0; i < 1000000; i++) { counter++; } System.out.println("t2 ends."); }); t2.start(); t1.join(); t2.join(); System.out.println("counter=" + counter); System.out.println("main() ends."); Thread t3 = new Thread(() -> { System.out.println("t3 starts."); for (int i = 0; i < 10000000; i++) { atomicCounter.incrementAndGet(); // similar to counter++ } System.out.println("t3 ends."); }); t3.start(); Thread t4 = new Thread(() -> { System.out.println("t4 starts."); for (int i = 0; i < 10000000; i++) { atomicCounter.incrementAndGet(); // similar to counter++ } System.out.println("t4 ends."); }); t4.start(); t3.join();//.join() means the main thread will wait for t3 and t4 to complete before proceeding. t4.join(); System.out.println("atomicCounter=" + atomicCounter.get()); } } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up