1,API:(newFixedThreadPool)
2,创建线程池:(使用Executors工具类)
//使用Executors工具类:
ExecutorService executorService = Executors.newFixedThreadPool(3);
3,使用Runnable接口提交任务:(提交:submit方法)
//main类:
public class Text02 {
public static void main(String[] args) {
//使用Executors工具类,创建线程池:
ExecutorService executorService = Executors.newFixedThreadPool(3);
//创建线程任务:
MyRunnable myRunnable = new MyRunnable();
//提交任务到线程池:
executorService.submit(myRunnable);
executorService.submit(myRunnable);
executorService.submit(myRunnable);
executorService.submit(myRunnable);
//关闭线程池:
executorService.shutdown();
}
}
//myRunnable:
public class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"\tend");
}
}
3,使用Callable提交任务:(提交:submit方法)
具有返回值:要创建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 {
private int n;
public MyCall(int n) {
this.n = n;
}
@Override
public Object call() {
int sum=0;
for (int i = 0; i < n; i++) {
sum+=i;
}
return sum;
}
} ```