1: Inherit Thread
public static void main(String[] args) throws ExecutionException, InterruptedException{ Thread01 thread01 = new Thread01(); thread01.start(); } public static class Thread01 extends Thread { @Override public void run() { System.out.println("Current thread" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("Operation results" + i); } }
2: implement Runnable interface
public static void main(String[] args) throws ExecutionException, InterruptedException{ Runnable01 runnable01 = new Runnable01(); new Thread(runnable01).start(); } public static class Runnable01 implements Runnable { @Override public void run() { System.out.println("Current thread" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("Operation results" + i); } }
3: implement callable + futuretask (you can get the returned results and handle exceptions)
public static void main(String[] args) throws ExecutionException, InterruptedException{ Callable01 callable01 = new Callable01(); FutureTask<Integer> integerFutureTask = new FutureTask<>(callable01); new Thread(integerFutureTask).start(); // Blocking waits for the entire thread to complete execution and gets the returned result Integer integer = integerFutureTask.get(); System.out.println("The results obtained"+integer); } public static class Callable01 implements Callable<Integer> { @Override public Integer call() throws Exception { System.out.println("Current thread" + Thread.currentThread().getId()); int i = 10 / 2; System.out.println("Operation results" + i); return i; } }
4 thread pool
Submit task ExecutorService to thread pool
1. Executors (the official method of creating thread pool directly, but it is not recommended in real projects) Executors.newCachedThreadPool(); //core is 0. All are recyclable Executors.newFixedThreadPool(10); // Fixed size, core = max; Are not recyclable Executors.newScheduledThreadPool(10); // Thread pool for scheduled tasks Executors.newSingleThreadExecutor(); // Single threaded thread pool 2. new ThreadPoolExecutor Seven parameters: 1.corePoolSize: number of core threads; The number of threads ready after the thread pool is created, and they wait to accept asynchronous tasks for execution 2.maximumPoolSize the maximum number of threads controls resources 3. keepAliveTime survival time. If the current number of threads is greater than the number of cores, free the idle threads (maximumPoolSize - corePoolSize). As long as the thread idle time is greater than the specified keepAliveTime, it is equivalent to dismissing the temporary worker 4. unit time unit 5. workQueue blocks the queue. If there are many tasks, the current many tasks will be placed in the team. As long as there are threads idle, they will go to the queue to take out new tasks and continue to execute. 6. threadFactory thread creation factory 7. If the queue is full, the handler will reject the task according to the specified rejection policy Operation process: 1. Create a thread pool, prepare the number of core threads, and prepare to accept tasks 2. New tasks come in and are executed with idle threads prepared by the core 1. When the core is full, put the incoming tasks into the blocking queue. The idle core will block the queue to get the task execution 2. When the blocking queue is full, a new thread is directly opened for execution. The maximum number can only be opened to the number specified by max 3.max has been executed. The Max - core number of idle threads will be automatically destroyed after the time specified by keepAliveTime. Finally, keep to the core size. 4. If the number of threads reaches max and a new task comes in, the reject policy specified by reject will be used for processing 3. All threads are created by the specified factory. Interview questions: A thread pool, core: 7 Max: 20 queue: 50 100 concurrent, how to allocate 7 will be executed immediately, 50 will enter the queue, 13 will be opened for execution, and the remaining 30 will use the reject policy Why use thread pool in development Reduce resource consumption Reduce the loss caused by thread creation and destruction by reusing the created threads Submit response speed Because when the number of threads in the thread pool does not exceed the maximum limit of the thread pool, some threads are waiting to allocate tasks. When tasks come, they can be executed without creating new threads Improve thread manageability The thread pool will optimize the threads in the pool according to the current system characteristics to reduce the system overhead caused by creation and destruction. Unlimited thread creation and destruction not only consume system resources, It also reduces the stability of the system and uses thread pool for unified allocation. difference: 1.2 cannot get the return value 3, you can get the return value 1.2.3 cannot control resources 4. Stable resource performance can be controlled