Java multithreading, concurrent programming knowledge point summary, java Multithreading

Source: Internet
Author: User
Tags thread stop

Java multithreading, concurrent programming knowledge point summary, java Multithreading

1. thread status

1.1 two ways to create a thread: interface and Thread class. Advantages of Using Interfaces: it better reflects the object-oriented thinking and avoids the limitations caused by Java's single inheritance feature;
Enhance the robustness of the program. The code can be shared by multiple threads, and the code and data are independent. (The synchronization problem) is suitable for processing the same resource in multiple thread zones with the same program code.


1.2 The thread is ready and waits for scheduling to run the start () method.


Thread interruption of 1.3

It should be noted that if the thread is not actually interrupted by simply calling the interrupt () method, it will continue to be executed.


1.4. Thread suspension and recovery (suspension also has Object locks and deadlocks)
The correct method for thread suspension and restoration is to set a flag to suspend the thread at a safe location.


1.5 The jion method is used to simulate synchronization using multiple threads. mThread. jion () indicates the thread that is called after the thread is run.


1.6 sleep

When the Thread executes Thread. sleep (), it is blocked until the specified millisecond time, or the blocking is interrupted by another Thread;


1.7stop thread stop

The stop method suddenly terminates the thread (there must be some proper reason to hold these locks -- maybe it is to prevent other threads from accessing data that is not in a consistent state,
The sudden release of the lock may cause data in some objects to be inconsistent)


1.8 threads can be blocked in four states:


When the Thread executes Thread. sleep (), it is blocked until the specified millisecond time, or the blocking is interrupted by another Thread;


When a thread encounters a wait () statement, it will be blocked until it receives the notification (notify y (), is interrupted, or has elapsed the specified Millisecond Time (if a timeout value is set)
There are multiple thread blocking methods and different I/O methods. A common method is the read () method of InputStream. This method is blocked until a byte of data is read from the stream. It can be blocked infinitely, so the timeout time cannot be specified.
The thread can also be blocked and wait for the exclusive access permission to obtain an object lock (that is, it is blocked when the synchronized statement is required ).


2. Thread types

Four cases of daemon thread and thread Blocking
Java has two types of threads: User Thread and Daemon Thread)
You can use the setDaemon (true) method of Thread to set the current Thread as the daemon Thread.


Whether the daemon thread has completed the expected service task. Once all user threads exit, the virtual machine exits.
Therefore, do not perform business logic operations (such as data reading and writing) in the daemon thread ). ,




SetDaemon (true) must be set before the start () method of the thread is called. Otherwise, an IllegalThreadStateException occurs.
The new thread generated in the daemon thread is also the daemon thread.
Do not think that all applications can be allocated to the daemon thread for service, such as read/write operations or computing logic.



3. Data operated by the thread

Synchronization problems:


4. reentrant built-in locks
Each Java object can be used as a synchronization lock. These locks are called built-in locks or monitor locks.
The thread automatically acquires the lock before entering the synchronization code block, and automatically releases the lock when exiting the synchronization code block.
The only way to obtain the built-in lock is to enter the synchronous code block or method protected by the lock.


A thread holding the synchronization object lock can enter this synchronization code block or method multiple times. That is, the synchronization object lock can be reentrant!
When the same thread calls other synchronized methods/blocks in this class or the synchronized methods/blocks in the parent class, the thread will not be blocked, because the mutex lock can be reentrant.






6. Java Memory Model
In the current Java memory model, the thread can store variables in the local memory (such as machine registers) rather than directly reading and writing in the main memory. (Local Memory + Shared primary memory)


Each time a member variable modified by Volatile is accessed by a thread, the value of the member variable is forcibly re-read from the shared memory. In addition, when the member variables change, the thread is forced to write the change value back to the shared memory.
In this way, two different threads always see the same value of a member variable at any time.
The volatile keyword is the prompt JVM: For this member variable, it cannot store its private copy, but should directly interact with the shared member variable.


Special rules for volatile variables:


1. ensure the visibility of this variable to all threads. Note that the write operation of the volatile variable is visible to the read operation itself, and all the shared variables before the volatile write operation are visible to the operations after the volatile read operation.
2. disable command re-sorting Optimization
The final domain ensures the security of the initialization process and allows unrestricted access to immutable objects without synchronization when sharing these objects.


Therefore, you do not need to declare the long and double variables as volatile during encoding.
Master memory and working memory


The Java memory model requires that all variables are stored in the primary memory, and each thread has its own working memory, the worker memory of the thread stores the copy of the master memory of the variables used by the thread,
All operations (read and value assignment) on variables by the thread must be performed in the working memory, rather than directly reading and writing the variables in the main memory.




According to the Java Virtual Machine specification, the volatile variable still has a copy of the shared memory, but due to its special operation sequence rules-before reading and writing data from the working memory,
The data in the primary memory must be synchronized to the working memory first. All data looks like reading and writing data directly in the primary memory. Therefore, the description here is no exception to volatile.




A thread is not allowed to discard its latest assign operation, that is, the variable must be synchronized back to the main memory after it is changed in the working memory.
If you perform the lock operation on a variable, the value of this variable in the working memory will be cleared. Before the execution engine uses this variable, you need to re-execute the load or assign operation to initialize the value of the variable.
Before performing the unlock operation on a variable, you must synchronize the variable back to the main memory (


7. Lightweight Synchronization
Volatile is a slightly weaker synchronization mechanism. when accessing the volatile variable, it does not execute the lock operation, nor does it execute thread blocking. Therefore, the volatilei variable is a more lightweight synchronization mechanism than the synchronized keyword.




Suggestion: use volatile on the member variables to be accessed by two or more threads. Volatile is unnecessary when the variable to be accessed is already in the synchronized code block or is a constant.
Because volatile is used to block the necessary code optimization in JVM, the efficiency is relatively low. Therefore, this keyword must be used when necessary.




If two threads read and write volatile variables respectively, thread A writes A volatile variable, and thread B reads the volatile variable, it can see the write operations of thread A on the volatile variable,
The key here is that it will not only see the write operation on the volatile variable, but also all the visible shared variables before thread A writes the volatile variable. After thread B reads the same volatile variable, will immediately become visible to line B.




Happen-before rule Introduction
That is to say, before operation B occurs, the impact of Operation A can be observed by Operation B, "Impact" includes modifying the value of shared variables in the memory, sending messages, and calling methods. It has little to do with the occurrence of time.
Thread startup rules: the start () method of the Thread object happen-before each action of this Thread.






8. Synchronization lock description
The thread can access this resource only when it has the lock tag. It enters the lock pool without the lock tag. Any object system will create a mutex lock for it,
This lock is intended to be allocated to the thread and prevent atomic operations from being interrupted. The lock of each object can only be assigned to one thread, so it is called a mutex lock.


If there are two or more threads in the same method, each thread has its own local variable copy.
Each instance of the class has its own object-Level Lock


Accessing the synchronization code block in different instance objects of the same class does not block the issue of waiting to obtain the object lock,
Because they obtain the object-level locks of their respective instances, they do not affect each other.


Holding an object-Level Lock will not prevent this thread from being exchanged, nor will it block other threads from accessing non-synchronized code in the same sample object.


The thread holding the object-Level Lock will block other threads out of all synchronized code.


You can use synchronized (obj) to synchronize statement blocks to obtain object-level locks on a specified object.




A class lock is shared by all examples of a specific class. It is used to control concurrent access to static member variables and static methods. The specific usage is similar to the object-Level Lock.






10. secure use of a set of APIs in a multi-threaded Environment




The initially designed Vector and Hashtable are multi-threaded and secure.


There are multiple static methods in the Collections class. They can obtain the set obtained by encapsulating a non-synchronous set through the synchronization method:



Public static List synchronizedList (list l)


List list = Collection. synchronizedList (new ArrayList ());
Note that the ArrayList instance is immediately encapsulated and there is no direct reference to the unsynchronized ArrayList (that is, the anonymous instance is directly encapsulated ).
This is the safest way. If another thread directly references the ArrayList instance, it can perform non-synchronous modifications.


From the perspective of memory visibility, writing the volatile variable is equivalent to exiting the synchronization code block, while reading the volatile variable is equivalent to entering the synchronization code block.




The volatile variable is a weak synchronization mechanism. when accessing the volatile variable, it does not perform the lock operation, so it does not block the execution thread, therefore, the volatile variable is a more lightweight synchronization mechanism than the synchronized keyword.




The reason is that the simple variable declared as volatile does not work if the current value is related to the previous value of the variable, that is, the following expressions are not atomic operations: "count ++" and "count = count + 1 ".


The volatile variable should be used only when all of the following conditions are met:
1. Write operations on variables do not depend on the current value of the variable, or you can ensure that only a single thread updates the value of the variable.
2. The variable is not included in the variant with other variables.






Iii. deadlock
The following principles help avoid deadlocks:




1. Only hold the lock within the shortest time required. Use the synchronous statement block instead of the entire synchronization method;
2. Try to write code that requires multiple locks at different times. If unavoidable, make sure that the thread holds the second lock for as short as possible;
3. Create and use a large lock to replace several small locks, and use the lock for mutual exclusion instead of the object-Level Lock of a single object;


4. Thread Communication




Before calling wait (), the thread must obtain the object-Level Lock of the object, that is, the wait () method can only be called in the synchronous method or synchronization block. After entering the wait () method, the current thread releases the lock.
Y () This method must also be called in the synchronous method or synchronization block. That is, before calling the method, the thread must also obtain the object-Level Lock of the object. If you call notify () the IllegalMonitorStateException will also be thrown.


Notify, the current thread will not immediately release this object lock. The thread where wait is located cannot immediately obtain this object lock. The lock will not be released until the program exits the synchronized code block, the thread where wait is located can also obtain the object lock ),
But do not disturb other threads that are waiting for the notify object. When the first wait thread that has obtained the Lock of this object finishes running, it will release the Lock of this object. If the object does not use the notify statement again, even if the object is idle,
Other threads waiting in the wait status will continue to be blocked in the wait status until this object sends a running y or policyall notification. Note that they are waiting for Y or notifyAll, rather than locking.


This is different from the execution of the policyall () method below.




NotifyAll causes all the threads that were originally wait on this object to exit the wait state (that is, all threads are awakened and no longer waiting for notify or notifyAll). However, this object lock has not been obtained yet, therefore, you cannot continue execution ),
Wait until the lock on the object is obtained. Once the lock is released (when the policyall thread exits and calls the synchronized code block of notifyAll), they will compete.
If one of the threads gets the object lock, it will continue to execute. After it exits the synchronized code block and releases the lock, other wake-up threads will continue to compete to obtain the lock and continue until all wake-up threads are executed.






If the thread calls the wait () method of the object, the thread will be in the waiting pool of the object, and the thread in the waiting pool will not compete for the lock of the object.
When a thread calls the notifyAll () method of the object (wake up all wait threads) or the notify () method (wake up only one wait thread randomly ), the wake-up thread will enter the lock pool of the object, and the thread in the lock pool will compete for the object lock.
A thread with a higher priority has a high probability of competing with the object lock. If a thread does not compete with the object lock, it will remain in the lock pool. Only the thread can call the wait () method again, it will return to the waiting pool again. The thread competing for the object lock continues to execute,
After executing the synchronized code block, the lock will be released, and the thread in the lock pool will continue to compete for the lock.








Summary: when using the thread wait/notification mechanism, it is generally necessary to use a boolean variable value (or other conditions that can determine whether the value is true or false) to change the value of this boolean variable before running y, after wait returns, it can exit the while loop.
(Usually add a while loop to the perimeter of the wait method to prevent early notifications), or after the notification is omitted, it will not be blocked in the wait method. This ensures the correctness of the program.






V. New Features of concurrency
1,
In general, CachedTheadPool usually creates the same number of threads as required during program execution, and stops creating new threads when it recycles old threads,
Therefore, it is the preferred choice for rational Executor. FixedThreadPool is required only when this method causes problems (for example, when a large number of connection-oriented threads are required.




Server-side connection oriented: public static ExecutorService newFixedThreadPool (int nThreads)




Executor executes the Runnable task
Executor executes the Callable task




After Java 5, there are two types of tasks: one is the class that implements the Runnable interface and the other is the class that implements the Callable interface. Both can be executed by ExecutorService,
However, the Runnable task does not return values, but the Callable task does. Besides, the call () method of Callable can only be executed through the submit (Callable <T> task) method of ExecutorService,
And return a <T> Future <T>, indicating the Future of the task waiting for completion.




The Callable interface is similar to Runnable, both of which are designed for classes whose instances may be executed by another thread. However, Runnable does not return results, and cannot throw an exception that has been checked, while Callable returns results,
In addition, an exception may be thrown when the returned results are obtained. The call () method in Callable is similar to the Runnable run () method. The difference is that there is a return value, and the latter does not.




When a Callable object is passed to the submit method of ExecutorService, the call method is automatically executed on a thread and the execution result Future object is returned. Similarly, the Runnable object is passed to the submit method of ExecutorService,
The run method is automatically executed on a thread and the Future object of the execution result is returned. However, if the get method is called on the Future object, null is returned.


2. Custom Thread Pool


ThreadPoolExecutor class, which has multiple constructor methods to create a thread pool


BlockingQueue <Runnable>




New Features of concurrency-Lock and condition variable





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.