[Java thread and thread pool]

Java thread and thread pool


introduction

Java is a high-level programming language widely used in software development. Its multi-thread support enables developers to take advantage of multi-core processors to implement concurrently executed programs.


Table of contents

  1. thread basics

    • 1.1 What is a thread
    • 1.2 The life cycle of threads
    • 1.3 Ways to create threads
  2. Thread Synchronization and Communication

    • 2.1 Thread synchronization
    • 2.2 Thread communication
  3. Java thread pool

    • 3.1 The concept of thread pool
    • 3.2 Advantages of thread pool
    • 3.3 Implementation of thread pool
    • 3.4 Use of thread pool

1. Thread basics

1.1 What is a thread

A thread is the smallest unit of program execution. It is a part of a process, and a process can contain multiple threads. Threads can execute concurrently and share process resources. The advantage of threads is that they can make full use of multi-core processors and improve the execution efficiency of programs.

1.2 The life cycle of threads

The life cycle of a Java thread includes the following states:

  • New (New): The thread is created but has not yet started execution.
  • Running (Runnable): The thread is executing or waiting for a CPU time slice.
  • Blocked (Blocked): The thread waits for the satisfaction of a certain condition, and does not consume CPU time slices in this state.
  • Waiting (Waiting): The thread waits for notification from other threads, and the thread in the waiting state can be woken up by other threads.
  • Timed Waiting: The thread automatically resumes running after waiting for a specified period of time.
  • Terminated: The thread finishes executing or terminates abnormally.

1.3 Ways to create threads

In Java, there are two main ways to create threads:

  • Inherit the Thread class: Create a thread by inheriting the Thread class and rewriting the run() method.
  • Implement the Runnable interface: Implement the Runnable interface and pass its instance to the constructor of the Thread class.

The following is a sample code for creating a thread by inheriting the Thread class and implementing the Runnable interface:

// 使用继承Thread类创建线程
class MyThread extends Thread {
    
    
    public void run() {
    
    
        // 线程执行的代码
    }
}

// 使用实现Runnable接口创建线程
class MyRunnable implements Runnable {
    
    
    public void run() {
    
    
        // 线程执行的代码
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 创建线程对象并启动线程
        MyThread thread1 = new MyThread();
        thread1.start();

        MyRunnable runnable = new MyRunnable();
        Thread thread2 = new Thread(runnable);
        thread2.start();
    }
}

2. Thread synchronization and communication

2.1 Thread synchronization

Data inconsistency or race conditions may result when multiple threads access shared resources. To avoid this, thread synchronization is required.

Java provides the keywords synchronizedand volatileto achieve thread synchronization. synchronizedKeywords are used to decorate methods or code blocks to ensure that only one thread executes the decorated code at the same time. volatileKeywords are used to modify variables, ensure the visibility of variables, and read the latest value from main memory every time they are accessed.

synchronizedThe following is a sample code for thread synchronization using keywords:

class Counter {
    
    
    private int count = 0;

    public synchronized void increment() {
    
    
        count++;
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Counter counter = new Counter();

        // 创建多个线程对计数器进行操作
        // ...

        // 等待所有线程执行完毕
        // ...
    }
}

2.2 Thread communication

Thread communication refers to the process of passing messages or sharing data among multiple threads. Java provides wait(), notify()and notifyAll()methods to achieve communication between threads.

  • wait()The method puts the thread into the waiting state and releases the lock resource.
  • notify()Method wakes up one of the waiting threads.
  • notifyAll()method to wake up all threads that are waiting.

The following is a sample code to implement the producer-consumer model using thread communication:

class Buffer {
    
    
    private int data;
    private boolean available = false;

    public synchronized void produce(int newData) {
    
    
        while (available) {
    
    
            try {
    
    
                wait();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }

        data = newData;
        available = true;
        notifyAll();
    }

    public synchronized int consume() {
    
    
        while (!available) {
    
    
            try {
    
    
                wait();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }

        available = false;
        notifyAll();
        return data;
    }
}

public class Main {
    
    
    public static void main(String[] args) {
    
    
        Buffer buffer = new Buffer();

        // 创建生产者线程和消费者线程
        // ...

        // 等待所有线程执行完毕
        // ...
    }
}

3. Java thread pool

3.1 The concept of thread pool

A thread pool is a mechanism for managing and reusing threads. It pre-creates a set of threads and maintains a task queue for storing pending tasks. When a task needs to be executed, the thread pool will obtain an idle thread from the task queue to execute the task, and the thread will return to the thread pool for reuse after execution.

3.2 Advantages of thread pool

Using a thread pool has the following advantages:

  • Reduce the overhead of thread creation and destruction: Thread creation and destruction are relatively expensive operations. Using a thread pool can avoid frequent creation and destruction of threads and improve system performance.
  • Control the number of concurrent threads: The thread pool can limit the number of concurrent threads in the system to prevent excessive thread competition from exhausting system resources.
  • Provides a task queuing and scheduling mechanism: the thread pool can manage the task queue, schedule tasks to execute according to a certain strategy, and avoid system crashes caused by task overload.

3.3 Implementation of thread pool

Java provides interfaces and classes java.util.concurrentunder the package to implement thread pool.ExecutorThreadPoolExecutor

ExecutorThe interface is the top-level interface of the thread pool, which defines the basic operation methods of the thread pool, such as executing tasks and closing the thread pool.

ThreadPoolExecutorThe class is Executorthe implementation class of the interface, which provides the concrete implementation of the thread pool. Parameters such as the number of core threads, the maximum number of threads, and the task queue of the thread pool can be specified through the constructor.

The following is a sample code for creating a thread pool and executing tasks:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(5);

        // 提交任务给线程池执行
        for (int i = 0; i < 10; i++) {
    
    
            executor.execute(new Task(i));
        }

        // 关闭线程池
        executor.shutdown();
    }

    static class Task implements Runnable {
    
    
        private int taskId;

        public Task(int taskId) {
    
    
            this.taskId = taskId;
        }

        public void run() {
    
    
            System.out.println("Task " + taskId + " is running.");
        }
    }
}

3.4 Use of thread pool

Multi-threaded programming can be simplified by using a thread pool. The following are common operations of the thread pool:

  • Create a thread pool: You can Executorscreate a thread pool through the factory methods provided by the class, such as newFixedThreadPool(), newCachedThreadPool()etc.
  • Submit task: Submit the task to the thread pool for execution by calling execute()the method or methods of the thread pool.submit()
  • Close the thread pool: When the thread pool is no longer needed, shutdown()the method of the thread pool should be called to close the thread pool and release resources.

Guess you like

Origin blog.csdn.net/qq_66726657/article/details/131955199