This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

concurrent

  • injavaThere are many ways to implement a concurrency in
    • Like implementing aRunableinterface
public class testRunable implements Runnable{
    @Override
    public void run(a) {
        System.out.println("test"); }}Copy the code
  • runMethod code is executed in a thread summary,
    • The execution of threads is mainly a few simple instructions provided by the operating system
    • There is no need to go task by task and thread by thread, which is a huge waste of resources
    • If we use thread pools, see the following figure

  • When we use thread pools,newCachedThreadPoolIt creates a lot of short tasks
    • Each task will then be executed on an idle thread

Create a thread

  • Itself inJavaThere are three ways to create a thread in
    • inheritanceThreadclass
    • implementationRunableinterface
    • useFutureTask

1.Thread

  • Call with a class objectstart()Start the thread
    • The process of starting is to getCPUResources, and then actually change to the running state

2.Runable

  • Return without tasks

3.FutureTask

  • Code implementationcallmethods
    • FutureTaskThe object’sget()The method is to wait for the task to complete and return the result

The thread pool

  • Thread pools are born for a number of reasons
    • First let’s think about single-threadedExecutorIf a task commits another task to the sameExecutor
    • However, waiting for the result of the first task to commit occurs, so this often causes deadlocks
public ThreadPoolExecutor(int corePoolSize,
                         int maximumPoolSize,
                         long keepAliveTime,
                         TimeUnit unit,
                         BlockingQueue<Runnable> workQueue,
                         ThreadFactory threadFactory,
                         RejectedExecutionHandler handler) 
Copy the code
  • The core base size, maximum number of threads, and lifetime of a thread pool are all responsible for thread creation and destruction
    • More threads are created when the work queue is full
    • But if a thread exceeds its lifetime, it will definitely be recalled