Java-Threading Basic concepts

Source: Internet
Author: User
Tags mutex sleep function thread class

Java Concurrency Programming-----thread Basic concepts

Thread state diagram

Description :
The thread altogether consists of the following 5 states.
1. new state : When the thread object is created, it enters the new state. For example, thread thread = new Thread ().
2. ready State (Runnable): Also known as "executable State". When the thread object is created, the other thread invokes the object's start () method to start the thread. For example, Thread.Start (). A thread that is in a ready state may be executed by the CPU at any time.
3. running State (Running) : Thread gets CPU permission to execute. It is important to note that a thread can only go from a ready state to a running state.
4. blocking State (Blocked) : The blocking state is a temporary stop for a thread that has abandoned the CPU usage for some reason. Until the thread is in a ready state, the opportunity to go to the running state is reached. There are three types of blocking:
(01) Wait for blocking--by calling the thread's Wait () method, to let the thread wait for the completion of a job.
(02) Synchronization blocking--the thread acquires a synchronized synchronization lock failure (because the lock is occupied by another thread), it goes into a synchronous blocking state.
(03) Other blocking-the thread enters the blocking state by calling the thread's sleep () or join () or making an I/O request. When the sleep () state times out, join () waits for the thread to terminate or time out, or the I/O process finishes, the thread is re-entered in a ready state.
5. Death Status (Dead) : The thread finishes executing or exits the run () method because of an exception, and the thread ends the life cycle.

The 5 states involved include the object class, the thread, and the synchronized keyword. We'll learn about this in a later chapter.
The object class , which defines the sleep/wake functions such as Wait (), notify (), Notifyall ().
The thread class , which defines a number of column-manipulation functions. For example, the sleep () sleep function, the interrupt () interrupt function, GetName () Gets the thread name, and so on.
synchronized, which is a keyword, distinguishes it from synchronized code blocks and synchronized methods. The function of synchronized is to have the thread get the synchronization lock of the object.
We'll analyze why Wait (), notify (), and so on are defined in the object class instead of in the thread class, when the Wait (), notify (), and other methods are described in detail later.

Before we learn Java concurrency, we need to understand some basic concepts: sharing, mutable, thread safety, thread synchronization, atomicity, visibility, and ordering.

Shared and mutable

To write thread-safe code, the core is to access the shared and mutable state.

"Sharing" means that a variable can be accessed concurrently by multiple threads. We know that the resources in the system are limited, and that different threads have equal rights to the resources. Limited, fair means competition, and competition can cause threading problems.

"mutable" means that the value of a variable can change over its life cycle. "mutable" corresponds to "immutable". We know that immutable objects must be thread-safe and never require additional synchronization (because an immutable object can never change its externally visible state as long as it is built correctly). So "mutable" means there is a risk of thread insecurity. Workaround:

1. You can encapsulate a variable in a method without sharing the state variable in the thread.

2. Modify the state variable to the immutable variable (final).

3. Use a synchronization policy when accessing state variables.

4. Use the atomic variable class.

Thread Safety

Thread safety is a relatively complex concept. Its core concept is correctness. The so-called correctness is that a certain kind of behavior and its norms are exactly the same, that is, its approximate and "what is known (we know it when we see it)". This class is thread-safe when multiple threads access a category, regardless of how the runtime environment is scheduled or how those threads will be executed alternately, and if no additional synchronization or collaboration is required in the keynote code, and the class behaves correctly. (citation: "Java Concurrency Programming Combat")

Thread synchronization

Threading through its core is a "same". The so-called "with" is the synergy, assistance, cooperation, "Synchronization" is the pace of cooperation yesterday, that is, according to the order of the sequence to run, that "you first, I wait, you finish, I do again."

Thread synchronization, that is, when a thread makes a function call, the call does not return until the result is obtained, and the method cannot be called by other threads. In general, we are talking about synchronous and asynchronous tasks, especially those that require other components to match or that require a certain amount of time to complete. In multithreaded programming, some of the more sensitive data is not allowed to be accessed by multiple threads at the same time, using thread synchronization technology, to ensure that data at any time at most one thread access, to ensure the integrity of the data.

The main mechanisms of thread synchronization are: Critical section, mutex, event, signal volume four ways

1, critical area: Through the serialization of multithreading to access public resources or a piece of code, fast, suitable for controlling data access. Only one thread is allowed to access the shared resource at any time, and if more than one thread attempts to access the public resource, the other threads that attempt to access the public resource will be suspended after one thread enters, and wait until the thread that enters the critical section leaves and the critical section is freed before other threads can preempt it.

2, Mutex: adopt mutually exclusive object mechanism. Only the thread that owns the mutex has access to the public resource, because there is only one mutex object, so that the public resources are not accessed by multiple threads at the same time. Mutual exclusion can not only realize the common resources security sharing of the same application, but also can realize the security sharing of common resources of different applications.

3. Semaphore: It allows multiple threads to access the same resource at the same time, but needs to limit the maximum number of threads that access this resource at the same time.

4, Event: the way to maintain the synchronization of threads by notification operation, it is also convenient to achieve the priority comparison of multiple threads operations.

"Citation: Baidu Encyclopedia"

Atomic Nature

The atom is the smallest unit in the world and indivisible. In the world of our programming, if an operation is indivisible, we call that Operation Atomic. For example: i = 0, this operation is indivisible, so the operation is atomic. If an operation can be split, then the operation is not atomic, such as i++. There is a thread-safety problem with non-atomic operations, and at this point we need to use a synchronization mechanism to ensure that these operations become atomic operations, ensuring thread safety.

Visibility of

Thread visibility refers to the visibility between threads, where a thread's modification of a state is visible to another thread, that is, the result of a thread modification, and another thread knows it immediately. For example, Volitile modified variables, you have visibility.

Order of

Order refers to the data unrelated variables in the case of concurrency, the actual execution of the results and single-threaded execution is the same, not because the problem of reordering causes unpredictable results. Volatile, final, synchronized, explicit locks are guaranteed to be orderly.

Java-Threading Basic concepts

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.