import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test1 { public static void main(String[] args) { /*List<String> strs = new ArrayList<String>(); strs.add("a"); strs.add("b"); strs.add("c"); strs.add("d"); strs.add("e"); ManualApplyTask task = new ManualApplyTask(strs); ExecutorService muthreadPool = Executors.newSingleThreadExecutor(); muthreadPool.execute(task); muthreadPool.shutdown(); while(!muthreadPool.isTerminated()){ try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println("手动代扣异常:"+e); } }*/ for(int i=0;i<3;i++){ List<String> strs = new ArrayList<String>(); strs.add("a"); strs.add("b"); strs.add("c"); strs.add("d"); strs.add("e"); Test1 test1 = new Test1(); test1.executeTask(strs); System.out.println("test end" + i); } System.out.println("main end"); } public void executeTask(List<String> strs){ ManualApplyTask task = new ManualApplyTask(strs); //起单独线程执行 ExecutorService executor = Executors.newCachedThreadPool(); Future<Integer> result = executor.submit(task); executor.shutdown(); System.out.println("executeTask end"); } class ManualApplyTask implements Callable<Integer> { private List<String> strs; public ManualApplyTask(List<String> strs){ this.strs = strs; } @Override public Integer call() throws Exception { synchronized (ManualApplyTask.class){ try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } for(String str : strs){ System.out.println(str); } System.out.println("task end"); } return 1; } } }
Future异步多线程加同步锁
最新推荐文章于 2025-06-26 09:18:20 发布