1,API:(newFixedThreadPool)

image.png

2,创建线程池:(使用Executors工具类)

  1. //使用Executors工具类:
  2. ExecutorService executorService = Executors.newFixedThreadPool(3);

3,使用Runnable接口提交任务:(提交:submit方法)

  1. //main类:
  2. public class Text02 {
  3. public static void main(String[] args) {
  4. //使用Executors工具类,创建线程池:
  5. ExecutorService executorService = Executors.newFixedThreadPool(3);
  6. //创建线程任务:
  7. MyRunnable myRunnable = new MyRunnable();
  8. //提交任务到线程池:
  9. executorService.submit(myRunnable);
  10. executorService.submit(myRunnable);
  11. executorService.submit(myRunnable);
  12. executorService.submit(myRunnable);
  13. //关闭线程池:
  14. executorService.shutdown();
  15. }
  16. }
  17. //myRunnable:
  18. public class MyRunnable implements Runnable{
  19. @Override
  20. public void run() {
  21. System.out.println(Thread.currentThread().getName()+"\tend");
  22. }
  23. }

3,使用Callable提交任务:(提交:submit方法)

  1. 具有返回值:要创建Future对象,再去获取返回值;(赋值调用) ```java //main: public class Text01 { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建线程池: ExecutorService p = Executors.newFixedThreadPool(3);

    //创建任务 MyCall myCall = new MyCall(1000);

    //提交任务并获取Future对象(变量名为:submit) Future submit = p.submit(myCall); //使用Future对象的变量获取返回值 Integer o = submit.get(); System.out.println(o); } }

//myCall: public class MyCall implements Callable {

  1. private int n;
  2. public MyCall(int n) {
  3. this.n = n;
  4. }
  5. @Override
  6. public Object call() {
  7. int sum=0;
  8. for (int i = 0; i < n; i++) {
  9. sum+=i;
  10. }
  11. return sum;
  12. }

} ```