What are the practical application scenarios for multithreaded programming?

Multi-threaded business scenarios

Multithreading used in actual business development:

1. When logging in with the SMS verification code, a separate thread is generally opened to call the SMS interface, and the main thread returns.

2. The ajax sending request method often used by the front end is asynchronous because it is multi-threaded.

3. Image upload business.

4. In the file service , the files uploaded by each node are classified. There are many stages, many nodes, and the speed is very slow. It takes 700ms for one or two hundred files. After using multi-threaded processing, tens of milliseconds can be solved. Efficiency It’s improved tenfold, and it’s good, users can no longer experience the feeling of lag.

Multithreading of the framework itself

1. Tomcat responds to requests in a multi-threaded manner. Hundreds of clients access tomcat, and a request is received by one thread.

2. The druid connection pool often used when the project connects to the database.

Multi-thread safety issues

To be clear, there will be no thread safety issues without operating shared variables.

There are thread safety issues, when to lock

Shared data may be operated by two threads at the same time, and then locked.

Don't think about thread safety when it comes to multithreading, and then I want to lock, what will happen to the lock? The efficiency becomes lower. If you use multiple threads, the main reason is to improve efficiency. You then put a lock on each thread. . All in all, the consequences of using locks indiscriminately and performance degradation are trivial or even stuck.

Efficiency and data security are a seesaw. When A is high, B is low. Using locks reasonably is the right solution.

Multi-threaded common problems: multi-threaded running and transferring parameters

The problem of multi-thread coordination, multi-thread itself has no execution order.
Sometimes you will encounter such a scene. I want to improve efficiency and use multi-threading, but the parameter transfer between the method and the method is messy. So many threads run at once, and the second thread needs the first thread. The result, how to do it.

join() method: After the thread that called the join() method ends, other threads can run.

The above picture is as follows:
Insert picture description here
Insert picture description here
Insert picture description here
Take another example:
Insert picture description here
Summary:

If you have two threads A, thread B, and thread B want to use the result of thread A, it can be said that the thread transfer problem, how to solve it?

You can use the join() method, but your execution speed will definitely slow down. What should I do?

You can take a trick and make a time difference . According to your own business, you don't necessarily have to trigger the user to run multithreading and finish the job ahead of time.

The user can't feel the time of tens of ms, but if multiple threads run together within this 100ms, you have to use the results of other threads, there will definitely be a problem. How many ms can the computer feel .

The simplest multi-threaded operation method

  1. Inherit the Thread class
  2. Implement Runnable interface, no return value, can not throw exception.
  3. Implement the Callable interface, have a return value, and can throw exceptions.
  4. Thread Pool.

The first:

public class MyThread extends Thread {
    
    
  public void run() {
    
    
   System.out.println("我的新线程!");
  }
}

It can also be used directly like this, anonymous inner class.
Insert picture description here
The second type:

public class Test implements Runnable {
    
    
    @Override
    public void run() {
    
    
        System.out.println("我的新线程!");
    }
}

The third type: the
Insert picture description here
fourth type:
Insert picture description here
pay attention

The start() and run() methods in the Thread class are used differently

Calling the start() method is equivalent to starting a new thread.

The run() method is called in the original thread, and no new thread is started.

Introduction to thread pools

When using multi-threaded programming, the number of threads is not the better, and always open new threads, which consumes a lot of resources. The resources consumed by you to process a piece of logic may only occupy 10% of the resources, and new threads destroy threads. The life cycle occupies 90% of resources.

So it’s better to recycle the thread. It’s not that you can go die if your thread executes this task. No, you can continue to earn Ferrari for your boss.

Threads are reused, but you can’t let the threads do you fools. What to do if you paddle every day? Just eat and not. Leaders don’t like threads like this, so the thread pool should manage you and let you not fight dogs Go chase the chicken.

Thread life cycle

A thread has a life cycle, and the thread pool has a state.

The thread has five stages and the thread pool has five states.

1. New

2. Ready

3. Run

4. Blocking

5. Termination

Thread pool status

RUNNING: accept new tasks and process queued tasks

SHUTDOWN: do not accept new tasks, but process queued tasks

STOP: Do not accept new tasks, do not process queued tasks, and interrupt ongoing tasks

TIDYING: All tasks have been terminated.

TERMINATED: Completed.

The simplest thread pool operation method

ThreadPoolExecutor class:
Insert picture description here
Insert picture description here
Insert picture description here
·························Key strikes··················· ······

int corePoolSize

The number of core threads, how many threads do you plan to need for this thread pool based on business needs. After the thread pool is created, the number of threads in the pool is 0, and a request is made to start a thread.

int maximumPoolSize

The maximum number of threads that the thread pool can create is determined by this parameter.

long keepAliveTime

The maximum idle time of a thread. This parameter is invalid for the core thread. The core thread is more powerful and no one can control it. The idle time will only take effect when the current thread> core thread, and if the idle time of a thread reaches this point, it will be terminated.

TimeUnit unit

时间单位。
TimeUnit.DAYS.
TimeUnit.HOURS.
TimeUnit.MINUTES.
TimeUnit.SECONDS.
TimeUnit.MILLISECONDS.
TimeUnit.MICROSECONDS.
TimeUnit.NANOSECONDS.

BlockingQueue workQueue

The thread waiting queue stores the tasks waiting to be executed.
ArrayBlockingQueue: Based on an array, the size is specified when it is created, and the queued tasks are limited.
LinkedBlockingQueue: Based on a linked list, an unbounded queue, after the core thread is full, all incoming tasks enter the queue until the resources are exhausted.
SynchronousQueue: Not a team, just create a new thread and perform tasks.

ThreadFactory threadFactory

Thread creation factory.

RejectedExecutionHandler handler

Rejection strategy, if the current thread has reached the maximum number of threads, the rejection strategy will be executed.
ThreadPoolExecutor.AbortPolicy: Throw an exception.
ThreadPoolExecutor.DiscardPolicy: Discard tasks without throwing exceptions.
ThreadPoolExecutor.DiscardOldestPolicy: Discard the first task in the queue, and then execute the task again.
ThreadPoolExecutor.CallerRunsPolicy: caller thread processing tasks

Overall process

The above parameter is for you to design a thread pool yourself. A very important point is the number of threads.
Current <core, create a new thread to process the request.
The core <current> is the largest and enters the waiting queue for execution.
Core=Max, create a thread pool of fixed size.
The maximum number of threads is infinite, and the thread pool is unlimited to open new threads.
The overall process is:
Step 1: Receive the request and determine the size of the current number of threads and the number of core threads:
··············If it is less than the number of core threads, a new thread will be opened to perform the task.
·············If it is greater than the number of core threads, enter the waiting queue.
Step 2: Wait for the queue and determine whether the queue is full. This step is very important, not only to determine whether the queue is full, but also to see the set queuing strategy.
············If it is not full, you can go in and wait for execution.
············If it is full and entry fails, different operations will be performed according to the corresponding queuing strategy.
Step 3: Determine the size of the current number of threads and the maximum number of threads
·············If it is greater than the maximum number of threads, execute the rejection strategy.
············ If the number of threads is less than the maximum number of threads, the task will be submitted for execution.

If you want to save trouble, you can directly use the JDK provided. Understand the meaning of these seven parameters, the following four will be ok.

1 、 newFixedThreadPool
Insert picture description here
2 、 newCachedThreadPool
Insert picture description here
3 、 newSingleThreadExecutor
Insert picture description here
4 、 newSingleThreadScheduledExecutor
Insert picture description here

Thread pool shutdown method

1. Shutdown: Shut down in an orderly manner. After the method is executed, no new tasks will be received, and all tasks in the queue will be shut down after execution.

2. shutdownNow: Forcibly close all unexecuted and executing tasks, shut down instantaneously, and return to unexecuted tasks.

··················································· ····························
Have you abandoned school

Guess you like

Origin blog.csdn.net/numbbe/article/details/109313814