Java multithreading: from entry to mastery, master the basic knowledge and application of multithreaded programming


"Java multithreading: from entry to mastery, master the basic knowledge and application of multithreaded programming"

Java is an object-oriented programming language with powerful multithreading support. Multi-threading can make the program perform multiple tasks at the same time during execution, thereby improving the operating efficiency and response speed of the program. This article will introduce the basics and applications of Java multithreading.

1. What is a thread

A thread is the smallest execution unit in an operating system, an entity in a process, and is responsible for executing a sequence of instructions in a program. Each thread has its own stack space, program counter and registers, etc., and they share the memory space and resources of the process.

2. How to create a thread

There are two ways to create threads in Java: inheriting the Thread class and implementing the Runnable interface. Here is sample code for both ways:

1. Inherit the Thread class

public class MyThread extends Thread {
    
    
    public void run() {
    
    
        // 线程执行的代码
    }
}

// 创建线程
MyThread myThread = new MyThread();
myThread.start();

2. Implement the Runnable interface

public class MyRunnable implements Runnable {
    
    
    public void run() {
    
    
        // 线程执行的代码
    }
}

// 创建线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();

Three, the state of the thread

Java threads have the following states:

  1. New state (New): The thread has been created but has not yet started execution.
  2. Running state (Runnable): The thread is running or waiting for the CPU to allocate a time slice.
  3. Blocked state (Blocked): The thread is suspended for some reason (such as waiting for I/O operations).
  4. Waiting state (Waiting): The thread suspends execution for some reason (such as calling the wait() method).
  5. Timed waiting state (Timed Waiting): The thread suspends execution for a period of time for some reason (such as calling the sleep() method).
  6. Terminated: The thread has completed execution or terminated due to an exception.

4. Thread synchronization

When multiple threads operate on shared data at the same time, it is easy to cause data inconsistency. In order to ensure the consistency and correctness of data, thread synchronization technology needs to be used. Java provides the synchronized keyword and the Lock interface to achieve thread synchronization.

1. The synchronized keyword

The synchronized keyword can modify methods and code blocks to protect shared data. When a thread acquires the lock of an object, other threads cannot access the object's synchronization methods and synchronization code blocks until the thread releases the lock.

public class MyThread {
    
    
    private int count = 0;

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

2. Lock interface

The Lock interface is a new thread synchronization mechanism in Java5, which is more flexible and controllable than the synchronized keyword. The Lock interface provides lock() and unlock() methods for acquiring and releasing locks.

public class MyThread {
    
    
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void add() {
    
    
        lock.lock();
        try {
    
    
            count++;
        } finally {
    
    
            lock.unlock();
        }
    }
}

Five, thread pool

The thread pool is a technology for reusing threads, which can avoid the overhead of frequently creating and destroying threads. Java provides Executors class and ThreadPoolExecutor class to implement thread pool.

// 创建线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);

// 提交任务
executorService.submit(new MyTask());

// 关闭线程池
executorService.shutdown();

6. Inter-thread communication

Inter-thread communication refers to the information exchange and cooperation between multiple threads during execution. Java provides wait(), notify(), notifyAll() methods and Condition interface to realize inter-thread communication.

1. wait(), notify() and notifyAll() methods

The wait () method can make the thread wait until other threads call the notify () or notifyAll () method to wake it up. The notify() method randomly wakes up a waiting thread, and the notifyAll() method wakes up all waiting threads.

public class MyThread {
    
    
    private Object lock = new Object();
    private boolean flag = false;

    public void waitThread() throws InterruptedException {
    
    
        synchronized (lock) {
    
    
            while (!flag) {
    
    
                lock.wait();
            }
            // 执行任务
        }
    }

    public void notifyThread() {
    
    
        synchronized (lock) {
    
    
            flag = true;
            lock.notifyAll();
        }
    }
}

2. Condition interface

The Condition interface is a new thread communication mechanism in Java5, which provides await(), signal() and signalAll() methods for more flexible thread communication.

public class MyThread {
    
    
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private boolean flag = false;

    public void awaitThread() throws InterruptedException {
    
    
        lock.lock();
        try {
    
    
            while (!flag) {
    
    
                condition.await();
            }
            // 执行任务
        } finally {
    
    
            lock.unlock();
        }
    }

    public void signalThread() {
    
    
        lock.lock();
        try {
    
    
            flag = true;
            condition.signalAll();
        } finally {
    
    
            lock.unlock();
        }
    }
}

Seven, thread safety class

Java provides many thread-safe classes, such as ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, etc., which can avoid thread safety problems caused when multiple threads access the same data structure at the same time.

ConcurrentHashMap<String, String> map = new ConcurrentHashMap<>();
map.put("key", "value");

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("item");

BlockingQueue<String> queue = new LinkedBlockingQueue<>();
queue.put("element");

8. Summary

This article introduces the basic knowledge and application of Java multithreading, including thread creation, state, synchronization, thread pool, inter-thread communication, etc. In multi-threaded programming, you need to pay attention to thread safety issues, and you can use synchronized keywords, Lock interfaces, volatile keywords, etc. to perform synchronization control. At the same time, Java provides many thread-safe classes, which can avoid thread safety problems caused by multiple threads accessing the same data structure at the same time.

In actual development, you should choose a suitable thread model and synchronization method according to the specific situation to avoid problems such as deadlock and starvation, and improve the reliability and performance of the program.

I am Amnesia, an otaku who loves technology. If you have any questions about the article, you can point it out in the message. Welcome to leave a message. You can also add my personal WeChat to study together and make progress together!
insert image description here

Guess you like

Origin blog.csdn.net/qq_42216791/article/details/129879782