Chào mọi người, em đang tập sử dụng executor. Em cấp 5 thread chạy 1 lúc. Tại sao thứ tự lúc chạy và thứ tự trong list future lại khác nhau và làm thế nào để thứ tự trong list future giống với thứ tự lúc chạy ạ.
System.out.println("bat dau chay" + Calendar.getInstance()); Callable callable1 = new Callable() { @Override public String call() throws Exception { System.out.println("task 1"); return "task --1"; } }; Callable callable2 = new Callable() { @Override public String call() throws Exception { System.out.println("task 2"); return "task --2"; } }; Callable callable3 = new Callable() { @Override public String call() throws Exception { System.out.println("task 3"); return "task --3"; } }; List<Callable> callables = new ArrayList(); callables.add(callable1); callables.add(callable2); callables.add(callable3); callables.add(callable1); callables.add(callable2); callables.add(callable3); callables.add(callable1); callables.add(callable2); callables.add(callable3); ExecutorService executorService = Executors.newFixedThreadPool(5); List<Future> futures = executorService.invokeAll(callables); for (Future f : futures) { System.out.println(f.get()); } System.out.println("ket thuc" + Calendar.getInstance()); executorService.shutdown();
1. bản chất bên trong thằng ExecutorService nó là 1 mớ các Thread và 1 cái Queue, em có thể xem ví dụ tại đây nên khi em gọi hàm
invokeAll
thì các thread sẽ cùng lao đầu vào lấy dữ task trong queue để thực thi, tốc độ hoàn thành của mỗi thread là khác nhau, nên nó không thể nào theo thứ tự được, kiểu như là có 5 cô gái và 5 ông con trai, 5 ông lấy 5 cô gái nhưng không chắc chắn được 5 cô này có bầu tuần tự được, có cô thì có ngay, có cô thì phải năm sau mới có chẳng hạn2. Đã là môi trường đa luồng thì em không nên nghĩ đến việc làm tuần tự nữa, tuy nhiên nếu em vẫn muốn làm tuần tự, em hãy chuyển
ExecutorService executorService = Executors.newFixedThreadPool(5);
thànhExecutorService executorService = Executors.newSingleThreadExecutor();
nhé, ví dụ em có thể xem tại đây nhé