java高并发编程(五)线程池
2021-07-12 19:05
标签:其他 ++ util comm 一个队列 时间 none gif i++ 摘自马士兵java并发编程 一、认识Executor、ExecutorService、Callable、Executors console: java高并发编程(五)线程池 标签:其他 ++ util comm 一个队列 时间 none gif i++ 原文地址:https://www.cnblogs.com/tenWood/p/9545492.html/**
* 认识Executor
*/
package yxxy.c_026;
import java.util.concurrent.Executor;
public class T01_MyExecutor implements Executor {
public static void main(String[] args) {
new T01_MyExecutor().execute(new Runnable(){
@Override
public void run() {
System.out.println("hello executor");
}
});
}
@Override
public void execute(Runnable command) {
//new Thread(command).run();
command.run();
}
}
/**
* 线程池的概念
*/
package yxxy.c_026;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class T05_ThreadPool {
public static void main(String[] args) throws InterruptedException {
ExecutorService service = Executors.newFixedThreadPool(5); //execute submit
for (int i = 0; i ) {
service.execute(() -> {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
}
System.out.println(service);
service.shutdown();
System.out.println(service.isTerminated());
System.out.println(service.isShutdown());
System.out.println(service);
TimeUnit.SECONDS.sleep(5);
System.out.println(service.isTerminated());
System.out.println(service.isShutdown());
System.out.println(service);
}
}
java.util.concurrent.ThreadPoolExecutor@53d8d10a[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
false
true
java.util.concurrent.ThreadPoolExecutor@53d8d10a[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
pool-1-thread-1
pool-1-thread-3
pool-1-thread-2
pool-1-thread-5
pool-1-thread-4
pool-1-thread-1
true
true
java.util.concurrent.ThreadPoolExecutor@53d8d10a[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
/**
* 认识future
*/
package yxxy.c_026;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
public class T06_Future {
public static void main(String[] args) throws InterruptedException, ExecutionException {
/*FutureTask
1000
false
1
true