Executors创建固定线程demo

来源:互联网 发布:韩国制衣软件 编辑:程序博客网 时间:2024/04/30 17:50

来了解一下多线程的使用,多线程执行任务,再也不用for来解决。大大提升性能。


package com.a;import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.CountDownLatch;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class ExecutorServiceTest {static int count = 10;static CountDownLatch latch = null;public static void main(String[] args) throws Throwable {ExecutorServiceTest a = new ExecutorServiceTest();List<Student> list = a.TestThread();System.out.println("最后返回对象个数=="+list.size());}//多线程执行任务public List<Student> TestThread() {List<Student> list = new ArrayList<>();Student student = null;ExecutorService executorService = null;try {latch = new CountDownLatch(count);executorService = Executors.newFixedThreadPool(count);// 10个线程for (int i = 0; i < count; i++) {Future<Student> future = executorService.submit(new Callable<Student>() {public Student call() throws Exception {Student stu = createObject();return stu;}});// 添加if (future != null && future.get()!= null) {student = future.get();list.add(student);}else {throw new NullPointerException();}latch.countDown();}latch.await();} catch (Exception e) {e.printStackTrace();}executorService.shutdown();return list;}public Student createObject() {Student stu = new Student();for (int i = 0; i < 1; i++) {System.out.println("开始创建对象");stu = new Student();}return stu;}}


0 0
原创粉丝点击