This is the first day of my participation in Gwen Challenge

Threads and processes

  • 1. An execution of a program, the basic unit of a system program; System running a program is a process from the creation, run, die process.
  • Thread: A smaller unit of execution in a process. More than one thread is created during the execution of a program. Multiple threads share the heap and method area; Each thread has its own program counter, virtual machine stack, and local method stack.

2. Several states of threads (6 kinds)

state The name of the state instructions
NEW The initial state The state thread has been created, but the start() method has not been called
RUNNABLE Running state Java threads collectively refer to the ready and Running states of the operating system as running.
BLOCKED The blocking state < current thread > is blocked on lock
WAITING Wait state Entering the state < current thread > requires waiting for < other thread > to do some specific action (notification or interrupt)
TIME_WAITING Timeout wait state Unlike WAITING, this state can return at a specified time
TREMINATED Termination status Indicates that < current thread > has finished executing

Gantt Title Project V5.0 dateFormat YYYY-MM-DD Section Milestone 1: A1, 2021-04-15, 20D 25D section Milestone 2 Task1 :2021-06-01, 15d Task2:10D Section Milestone 3 Task1 :2021-07-16, 15D Task2:15D Section Milestone 4 Task1 :2021-09-01, 15D Task2 :20d

The concept and benefits of thread pool

Pooling technology

Database connection pool, HTTP connection pool, thread pool….

benefits

  • Reduce resource consumption and improve resource utilization.
  • Provides a way to limit and manage resources (including performing a task).
  • Each thread pool also maintains some basic statistics, such as the number of completed tasks.

4. Thread creation mode (4 ways)

1. Inherit the Thread class

class Thread: public void run(); // The @override method has no return value

2. Implement the Runnable interface

interface Runnable: public abstract void run(); Method has no return value

3. Create threads using Callable and Future

interface Callable: V call() throws Exception; Method has a return value

4. Use thread pools such as ThreadPoolExecutor framework, ali’s recommended ThreadPoolExecutor to create threads

  • Executor (not recommended)
  • ThreadPoolExecutor (recommended)

Executor Framework creates threads (not recommended)

  • FixedThreadPool (reusable thread pool with fixed number of threads)

FixedThreadPool uses the unbounded queue LinkedBlockingQueue (queue size integer.max_value) for thread pool work

  • SingleThreadExecutor (single threaded thread pool)

The queue length of allowed requests is integer. MAX_VALUE, which may accumulate a large number of requests and result in OOM.

  • CachedThreadPool (cacheable thread pool)

The thread pool where new threads will be created as needed (number of threads 0-integer.max_value)

  • ScheduledThreadPool (thread pool for timed and periodic execution)

ThreadPoolExecutor creates threads (recommended)

1. Construction method and main parameters

    public ThreadPoolExecutor(
        intCorePoolSize, // The number of core threads in the thread poolintMaximumPoolSize, // The maximum number of threads in the thread poollongKeepAliveTime, // When the number of threads is greater than the number of core threads, TimeUnit unit for keepAliveTime BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler // RejectedExecutionHandler handler // We can customize policies to handle tasks when there are too many submitted tasks to be processed in a timely manner.) {... }Copy the code

The three most important parameters of ThreadPoolExecutor are:

  • The number of threads defines the minimum number of threads that can run at the same time.
  • MaximumPoolSize: When the number of tasks in the queue reaches the queue capacity, the number of threads that can run simultaneously becomes the maximum number of threads.
  • WorkQueue: When a new task arrives, the system determines whether the number of threads currently running has reached the core number. If so, the new task is placed in the queue.

ThreadPoolExecutor other common parameters:

  • KeepAliveTime: when the number of threads in the thread pool is greater than corePoolSize, if no new task is submitted at this time, the threads outside the core thread will not be destroyed immediately. Instead, they will wait until the keepAliveTime exceeds the keepAliveTime before being recycled and destroyed.
  • Unit: keepAliveTime Time unit.
  • ThreadFactory: Used when executor creates a new thread.
  • Handler: saturation policy.

2. Several work queues for thread pools

  • ArrayBlockingQueue (bounded queue)
  • LinkedBlockingQueue (configurable capacity queue)
  • DelayQueue
  • PriorityBlockingQueue
  • SynchronousQueue

3. Four rejection strategies

Vii. Comparison of several common methods

  • Callable and Runnable interfaces
  • Execute () and submit() methods
  • The shutdown() and shutdownNow() methods
  • IsTerminated () and isShutdown() methods

How to ensure that threads are executed in sequence

  1. Single threaded thread pool SingleThreadExecutor
  2. The thread’s join() method
  3. The thread’s wait() method
  4. The CountDownLatch method for the thread
  5. Semaphore methods for threads
  6. The thread’s Condition method
  7. CyclicBarrier methods for threads

Reference links:

  • Javaguide thread pool learning summary
  • Java thread pool parsing
  • Java- Multithreading: The difference between the Callable and Runnable interfaces
  • Let the thread execute eight methods in order