1, Java why use multithreading the use of multithreading, you can put some large tasks into a number of small tasks to execute, between a number of small tasks do not image, at the same time, so that make full use of CPU resources.

2, Java in a simple way to achieve multithreading

Inherit Thread class, rewrite the run method;

Class Mythread extends Thread{public void run() {system.out.println (thread.currentThread ().getName()); }}Copy the code

Runable interface to achieve the run method;

Public void run() {system.out.println (thread.currentThread ().getName()); }}Copy the code

Enable:

Class ThreadTest {public static void main(String[] args) {Mythread = new Mythread(); thread.start(); MyRunnable MyRunnable = new MyRunnable(); Threadrunnable = new Thread(myRunnable); runnable.start(); Start a thread}}Copy the code

Java thread state creation: when a new thread is created without calling start, the thread is in the created state; Ready: The thread is ready when start is called, that is, the thread scheduler has not set up to execute the current thread; Run: when the scheduler runs to a thread, the current thread transitions from the ready state to the running state and starts executing the code in the run method. Block: A thread that is suspended while it is running (usually until a resource is ready to execute, sleep or wait can cause the thread to block). Death: A thread terminates when it finishes executing the code in the run method or calls the stop method

When we need a large number of concurrent threads to execute, and each thread completes in a short time, the frequent creation and destruction of threads (thread creation and destruction require time and resources) greatly reduces productivity. Thread pooling in Java improves thread utilization by allowing a thread to complete a task and proceed to the next task without being destroyed.

5, in Java thread pool (ThreadPoolExecutor) speak in Java thread pool, just think of Java. Util. Concurrent. ThreadPoolExecutor. The ThreadPoolExecutor class is the core class in the Java thread pool. He did it in four ways:

Public class ThreadPoolExecutor extends AbstractExecutorService {public ThreadPoolExecutor(int corePoolSize, Int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory ThreadFactory {this(corePoolSize, maximumPoolSize, KeepAliveTime, Unit, workQueue, threadFactory, defaultHandler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), handler); } public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {if (corePoolSize < 0 | | maximumPoolSize < = 0 | | maximumPoolSize The < corePoolSize | | keepAliveTime < 0) throw new IllegalArgumentException (); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }Copy the code

ThreadPoolExecutor class AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService: AbstractExecutorService CorePoolSize: size of the thread pool. Instead of creating a thread immediately after the thread pool is created, it waits for the thread to arrive. When the number of threads currently executing is greater than the value, threads are added to the buffer queue. MaximumPoolSize: the maximum number of threads created in the thread pool; KeepAliveTime: How long it takes for idle threads to be destroyed. By default, if the number of threads is greater than corePoolSize, the value is applied to threads that exceed corePoolSize. Unit: a value of the TimeUnit enumeration type, representing the keepAliveTime unit. The value can be: timeunit. DAYS; / / day TimeUnit. HOURS; / / hour TimeUnit. MINUTES; / / minutes TimeUnit. SECONDS; / / SEC TimeUnit. MILLISECONDS; / / ms TimeUnit. MICROSECONDS; / / subtle TimeUnit. NANOSECONDS; // nanosecond workQueue: a queue used to store tasks waiting to be executed, which determines the queue policy of the thread pool. LinkedBlockingQueue; SynchronousQueue; ThreadFactory: a threadFactory used to create threads. The default new Executors. DefaultThreadFactory (); Handler: indicates the thread rejection policy. When creating the thread beyond maximumPoolSize, and buffer queue is full, the new task will refuse, has the following values: ThreadPoolExecutor. AbortPolicy: discard task and throw RejectedExecutionException anomalies. ThreadPoolExecutor. DiscardPolicy: discard task too, but I don’t throw an exception. ThreadPoolExecutor. DiscardOldestPolicy: discard queue in front of the task, and then to try to perform a task (repeat) ThreadPoolExecutor. CallerRunsPolicy: handle the tasks by the calling thread

Enable:

Private void test2(){ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); Executor. SetMaxPoolSize (15); Executor. SetKeepAliveSeconds (1); executor.setQueueCapacity(5); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); Executor.execute (new Runnable(){@override public void run() {// Execute code}}); }Copy the code

Spring thread pools are implemented by the ThreadPoolTaskExecutor class. This class also ends up calling some of the methods in Java’s ThreadPoolExecutor class. Specific implementation readers can browse Spring source code, here the author will not list. Let’s look at the initialization of ThreadPoolTaskExecutor. ThreadPoolTaskExecutor has two common initialization methods: XML configuration, Java code initialization XML configuration:

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="5" />
    <property name="keepAliveSeconds" value="200" />
    <property name="maxPoolSize" value="10" />
    <property name="queueCapacity" value="20" />
    <property name="rejectedExecutionHandler">
        <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" />
    </property>
</bean>
Copy the code

Enable:

Public MyThreadPoolTaskExecutor {@autoWired private ThreadPoolTaskExecutor taskExecutor; Private void test(){taskExecutor.execute(new Runnable(){@override public void run() {// Execute code}});  }}Copy the code