线程池使用步骤:
1、自定义线程池
private ThreadPoolExecutor executor; /** * 初始化线程池 */ @PostConstruct private void init(){ int processors = Runtime.getRuntime().availableProcessors(); int corePoolSize = processors * 2; LinkedBlockingQueue queue = new LinkedBlockingQueue(); // 自定义线程池 executor = new ThreadPoolExecutor(corePoolSize, corePoolSize * 2, 60, TimeUnit.SECONDS, queue, new ThreadPoolDemoFactory("demo")); log.info("CorePoolSize: {}", executor.getCorePoolSize()); log.info("MaximumPoolSize: {}", executor.getMaximumPoolSize()); }View Code
2、给多线程构造任务
/** * 使用多线程,批量插入数据到MySql */ @RequestMapping("/") private void batchSave2MySql() throws SQLException { // 创建一个存储CompletableFuture的数组,存储异步调用的对象 List<CompletableFuture<?>> futures = new ArrayList<>(1000000); Connection conn = MySqlUtils.getConn(); Device device1 = new Device(); Device device2 = new Device(); device1.setName("device1"); device1.setTypeId(1); device2.setName("device2"); device2.setTypeId(2); List<Device> list = Lists.newArrayList(); list.add(device1); list.add(device2); // 给多线程构造任务 for(Device device : list){ PreparedStatement stmts = conn.prepareStatement ("insert into device values(?,?,?)"); stmts.setString(1, UUID.randomUUID().toString()); stmts.setString(2, device.getName()); stmts.setInt(3, device.getTypeId()); // 多线程执行后的返回结果在哪?? CompletableFuture future = CompletableFuture.supplyAsync(() -> { try { return stmts.execute(); } catch (SQLException e) { throw new RuntimeException(e); } }, executor); futures.add(future); } }View Code
3、多线程执行(自动)
git:https://gitee.com/caesarthegreat/thread-pool-demo.git
标签:Java,stmts,device1,device2,池化,new,线程,多线程 From: https://www.cnblogs.com/caesar-the-great/p/17064567.html