1. Thread status
2. Creating and using multi-threads
3. Thread synchronization
4. Synchronization collection
Thread status
Threads have five states: new, ready, running, blocked or ended.
New: Create a new thread, and the thread enters the new state;
Ready: After calling the thread's start() method to start the thread, it enters the ready state;
Run: When you get CPU time, the thread enters the running state from the ready state. If the time slice expires or the yield() method is called, the running state thread may enter the ready state;
Blocking: call join(), sleep(), or wait () method, or waiting for the I/O to end, the thread is in a blocked state;
Complete: When the thread finishes executing the run() method, the thread ends.
Creating and using multi-threads
Thread’s class diagram
1. Inherit the Thread class to create a new thread
2. Implement the Runnable interface and rewrite run( ) method
#Thread synchronization If a shared resource is accessed by multiple threads at the same time, it may be damaged. For example, if the data fields are modified in different orders, the final value may be uncertain.
Competition state: If two or more tasks access a common resource in a way that will cause conflicts, it is called a competition state
To avoid a competition state, multiple threads should be prevented At the same time, enter a specific part of the program. This part of the program is called a critical section.
1. Using lock synchronization
Java can explicitly use locks and states to synchronize threads. A lock is an instance of the Lock interface, which defines methods for locking and releasing locks.
RenntrantLock is an implementation of Lock, used to create mutually exclusive locks. Locks can be created for specific fairness policies. A fair policy value of 1 is true, ensuring that the thread with the longest waiting time acquires the lock first. If false, it is given to any waiting thread.2. Thread collaboration
Objects created by calling the newCondition() method of the Lock object can be used await(), signal() and signalAll() methods to achieve mutual communication between threads.
When a thread calls the await() method, the thread enters the waiting state, waiting for the wake-up signal.
3. Blocking queue
can block the current thread. If a thread takes elements from an empty blocking queue, the thread will be blocked until there are elements in the queue. The blocked queue will be automatically awakened, which provides great convenience.
Several blocking queues:
1: ArrayBlockingQueue uses an array to implement a blocking queue, and a capacity or optional fairness strategy must be specified to construct2: LinkedBlockingQueue uses a linked list to implement a blocking queue. Can be created unbounded or bounded.
3: PriorityBlockQueue priority queue, sorts elements according to their priority.
ArrayBlockingQueue data field
##It can be seen that the storage space is an array, and a lock is used.
Wait when the queue is full, and enter the queue when it is not full. At this time, use lock synchronization
Queue Wait when empty and leave the queue when not.
Blocking Queue Application
By As can be seen from the example, the producer puts numbers into the queue, the consumer takes the numbers from the queue, and waits when the queue is empty. Synchronization has been implemented in the queue without using locks and conditions.
3. Semaphores
Semaphores refer to objects that access common resources. Before accessing a resource, a thread must obtain permission from the semaphore. After accessing the resource, the permission must be returned to the semaphore.
The program creates a semaphore with a permission. When a thread is granted permission, other threads cannot access the resource until the previous thread releases the permission.
Synchronized Collections
Classes in the Java Collections framework are not thread-safe; that is, if they are accessed by multiple threads at the same time and Update, their contents may be corrupted, the data in the collection can be protected by locking the collection or synchronizing the collection
Related articles:
Java Implementation of get, PUT, POST, delete requests
Detailed introduction to Java programming common problems summary
Diagram of Java remote communication technology and principle analysis Text introduction
The above is the detailed content of Detailed explanation of Java multithreading basics. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

SublimeText3 Chinese version
Chinese version, very easy to use