1. Overview of the thread pool ideas
- Frequent elimination and create a thread takes time, repeated use of the same thread can improve efficiency
2. The concept of the thread pool
- Thread pool: a collection of threads
LinkedList<Thread> threads = new LinkedList<>();
Add Thread:
LinkedList<Thread> threads = new LinkedList<>();
threads.add(new Thread("线程1"));
threads.add(new Thread("线程2"));
threads.add(new Thread("线程3"));
threads.add(new Thread("线程4"));
The calling thread:
Thread thread01 = threads.removeFirst();
Thread thread02 = threads.removeFirst();
After use, also back thread
threads.addLast(thread01);
threads.addLast(thread02);
After JDK1.5:
- Use the thread pool factory class
Executors
inside a static method ofnewFixedThreadPool()
producing a specified number of thread pool
ExecutorService es = Executors.newFixedThreadPool(3); 生产3个线程,
- Creating a
Runnable
class that implements the interface, rewriterun()
method, set the thread task
public class ImpRunnable implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
- Using the
ExecutorService
methodsubmit()
, passing threaded tasks (implementation class), open thread executionrun()
method
es.submit(new ImpRunnable());
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo05 {
public static void main(String[] args) {
ExecutorService es= Executors.newFixedThreadPool(3);
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
es.submit(new ImpRunnable());
}
}
- Using the
ExecutorService
method ofshutdown()
destruction thread pool (not recommended)
es.shutdown();