1. 线程池
1. 背景
经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
2. 思路
提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中,使用时时直接获取,使用完放回池中,可以避免频繁创建和销毁,实现从重复利用。
3.好处
- 提高响应速度
- 降低资源消耗
- 便于线程管理
4.线程池使用
- JDK5.0起提供了线程池相关的API:ExecutorService和Executors
- ExecutorService:真正的线程池接口。常见子类ThreadPoolIExecutor
package Demo06;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1. 创建服务,创建线程池
//newFixedThreadPool 参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyTestPool());
service.execute(new MyTestPool());
service.execute(new MyTestPool());
service.execute(new MyTestPool());
service.execute(new MyTestPool());
//2.关闭线程池
service.shutdownNow();
}
}
class MyTestPool implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName());
}
}
}
2. 线程总结
package Demo06;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结
public class ThreadSummary {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
FutureTask futureTask = new FutureTask<Integer>(new MyCallable());
new Thread(futureTask).start();
try {
Object o = futureTask.get();
System.out.println(o);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
//1.继承thread类
class MyThread extends Thread{
@Override
public void run() {
System.out.println("MyThread");
}
}
//2.实现Runnable接口
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("MyRunnable");
}
}
//3.实现Callable接口
class MyCallable implements Callable{
@Override
public Object call() throws Exception {
System.out.println("MyCallable");
return 10;
}
}