Home > Java > javaTutorial > Detailed explanation of Java multithreading basics

Detailed explanation of Java multithreading basics

迷茫
Release: 2017-03-28 15:36:08
Original
2211 people have browsed it

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

##PrintChar implements the Runnable interface and uses Thread creates a thread. Since the Thread class implements the Runnable interface, you can create an object of this class and call its start method to start the thread.

3. Thread pool

Java provides the Executor interface To execute tasks in the thread pool, the ExecutorService interface is provided to manage and control tasks.

#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 construct

2: 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.

Implementation of two important methods

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template