The thread pool
- Threads are precious memory resources. A single thread occupies 1MB of space. Excessive allocation may cause memory overflow
- Frequent creation and destruction of threads increases vm reclamation frequency, resource overhead, and program performance degradation
- Hence the thread pool
The concept of thread pools
- A thread container that sets an upper limit on the number of threads allocated
- Pre-created thread objects are pooled and reused from the thread pool
- Avoid frequent creation and destruction
Principle of thread pool
Getting the thread pool
Creating a thread pool
public class TestThreadPool { public static void main(String[] args) { // 1. Creates a fixed number of threads thread pool objects / / thread pool can exist four threads ExecutorService es = Executors. NewFixedThreadPool (4); Runnable Runnable = new Runnable() {private int ticket = 100; // 2. @Override public void run() { while (true) { if(ticket <= 0) { break; } system.out.println (thread.currentThread ().getName() + "buy" + ticket--); }}}; For (int I = 0; i < 5; i++) { es.submit(runnable); } // 4. Close the thread pool es.shutdown(); }}Copy the code
The execution result
note
/ / 1. Create a single thread thread pool ExecutorService es = Executors. NewSingleThreadExecutor (); / / 1. Create a buffer pool, the number of threads by the task to decide the ExecutorService es = Executors. NewCachedThreadPool ();Copy the code
Callable interface
public interface Callable<V>{
public V call() throws Exception;
}
Copy the code
- JDK5 is added, similar to the Runnable interface, to represent a thread task when implemented
- Callable has generic return values and can declare exceptions
The Future interface
- Concept: Asynchronously accept the status result returned by executorService.submit (), which includes the return value from Call ()
- Method :V get() blocks for the result of asynchronous processing in the Future (return value of call())
The sample
- Use Future and Callable interfaces
- Using two threads, calculate the sum of 1-50 and 51-100 simultaneously, and then summarize
Public class TestCallable {public static void main(String[] args) throws Exception {// 1. Create a thread pool objects ExecutorService es = Executors. NewFixedThreadPool (2); // 2. Submit the task and get the Future object. Future<Integer> FUture1 = es. Submit (new Callable<Integer>() {@override public Integer Call () throws System.out.println("start 1-50 count... ); int sum = 0; for(int i = 1; i <= 50; i++) { sum += i; } return sum; }}); Future<Integer> future2 = es.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("start 51-100 count...") ); int sum = 0; for(int i = 51; i <= 100; i++) { sum += i; } return sum; }}); System.out.println(" + (future1.get() + future2.get())) "); // 4. Close the resource es.shutdown(); }}Copy the code
The results of
The Lock interface
- JDK5 added, compared with synchronized, display definition, structure more flexible
- Provide more practical methods, more powerful functions, better performance
Commonly used method
Void lock() // Try to acquire the lock(successful true, failed false, not blocked) Boolean tryLock // Release the lock void unlock()Copy the code
// Example public class TestLock implements Runnable {Lock l = new ReentrantLock(); private int ticket = 100; @Override public void run() { while (true) { l.lock(); try { if(ticket <= 0) { break; } System.out.println(Thread.currentThread().getName() + " sells " + ticket--); } catch (Exception e) { e.printStackTrace(); }finally { l.unlock(); } } } public static void main(String[] args) { ExecutorService es = Executors.newFixedThreadPool(4); for(int i = 0; i < 4; i++) { es.submit(new TestLock()); } es.shutdown(); }}Copy the code
The execution result
Thread-safe collection
Tool methods in Collections
Queue interface (Queue)
Public class TestQueue {public static void main(String[] args) {// 1. PriorityQueue<String> q = new PriorityQueue<String>(); Q.ffer ("a"); q.offer("b"); q.offer("c"); q.offer("d"); q.offer("e"); System.out.println(q.prinl ()); // 3. System.out.println(q.poll()); System.out.println(q.poll()); System.out.println(q.poll()); System.out.println(q.poll()); }}Copy the code
The execution result
The last
Thank you for reading here, after reading what do not understand, you can ask me in the comments section, if you think the article is helpful to you, remember to give me a thumbs up, every day we will share Java related technical articles or industry information, welcome to pay attention to and forward the article!