The core technical summary of multithreaded programming (read Zhou Zhiming book summary)

Source: Internet
Author: User
Tags garbage collection mutex thread class

Summary of core technology of multithreading programming

1.Java Multithreading Basic Skills

1.1 Concepts of processes and threads:

A process is a separate program, and a thread is a subtask that runs independently in a process.

1.2 Using multithreading

1.2.1 Implementation method: Inherit the thread class, overriding the Runnable interface.

1.2.2 Thread safety issues: Concurrent modification of common instance variables, i++,i--

1.3 Some methods of threading the thread class:

CurrentThread () put back the code snippet being called by that thread

IsAlive () to determine if the thread is active

Sleep () causes the current thread to exit the CPU fragment and wait for the lock to be acquired

1.4 Stopping a thread

1.4.1 using the Interrupt () method does not cause the thread to stop executing immediately, but instead makes a paused token.

this.interrupted (): Test if the front thread has been interrupted, this.isinterrupted (): Test if the front thread has been interrupted.

1.4.2 common methods for stopping threads-Exception method (throws exception)

1.4.3 at Sleep (), go to interrupted.

The effect of the 1.4.4 yield () method is to discard the current CPU resources, abandon how long the uncertainty is, and immediately join the CPU competition.

1.5 Thread Priority

The priority level varies from 1-10 and is set with the SetPriority () method, but the precedence is random and the priority is not necessarily first executed.

1.6 Daemon Threads

Java threads have two kinds, one is the daemon thread (Daemon) and the other is the user thread, and the garbage collection thread is the typical daemon thread. The daemon thread facilitates the operation of other threads, and when all other threads end, the guard line friend with the JVM to end the work.

2. concurrent access to objects and variables

Thread safety issues occur in instance variables, and there is no thread safety issue if the private variable is inside the method.

2.1synchronized Synchronization method

(1) Synchronized obtains the object lock, the thread executes the method with the Synchronized keyword first, the thread holds the lock of the object that the method belongs to, other threads that access the same object can only wait;

(2) Only the shared resources of reading and writing need to do synchronization;

(3) A thread first holds the lock on the object, and the B thread can invoke the non-synchronized method of the object in an asynchronous manner.

A thread first holds the lock on the object, and if the B thread calls the Synchronized method of the object, it needs to wait for synchronization.

(4) Synchronized lock re-entry: The Synchronized method internally calls this class of other synchronized methods, is always able to get the lock.

(5) An exception occurs and the lock is automatically released. Synchronization does not have inheritance.

2.2 Synchronized Synchronous statement Block

The synchronized method is to lock the current object, while the synchronized code block locks an object. Synchronized method is inefficient and synchronized code blocks are more granular

(1) Synchronized synchronization method

1) The Synchronized method or synchronized (this) synchronization code block for the other same object is blocked.

2) Only one thread can execute the code in the synchronized synchronization method at the same time

(2) synchronized (this) synchronous code block

1) The Synchronized method or synchronized (this) synchronization code block for the other same object is blocked.

2) Only one thread at a time can execute code in the synchronized (this) synchronous code block

(3) Synchronized (object x) synchronous code block

1) When multiple threads hold the object monitor as the same object, only one thread can execute the synchronized (object x) synchronization code block at the same time;

2) with "Object Monitor" as the same object, only one thread can execute synchronized (object x) synchronization code block at the same time.

The object monitor must be the same object that is synchronous, otherwise it is called asynchronously.

(4) Static synchronous synchronized method and synchronized (class) code block

When the Synchronized keyword is used on the static method, if so, it is the same as locking the current class with the synchronized (class) code block. When the Synchronized keyword is used on a non-static method, it is a lock on the object of the current class if it is written like this.

(5) Multi-threaded deadlock: For example, two objects hold an object lock, in the synchronous method (or block) inside the same request object lock of another object.

(6) As long as the object is not changed, even if the object property is changed, the result of the operation is synchronized.

2.3 Volatile Modifier Properties

(1) volatile forces the value of the variable to be taken from the public stack instead of the variable value from the thread private data stack.

(2) Comparison of volatile and synchronized keywords

1) volatile is a lightweight implementation of thread synchronization, and its performance is certainly better than synchronized, and volatile can only modify variables, and synchronized can modify methods, blocks of code.

2) Multi-threaded access volatile does not block, and synchronized can become blocked.

3) volatile guarantees the visibility of data, does not guarantee atomicity, and synchronized can guarantee the visibility of both atomicity and indirection.

4) Volatile resolves the visibility of variables across multiple threads, while synchronized solves the synchronization of access resources between multiple threads. Thread safety consists of atomicity and visibility.

Threads working in Memory: Read (load use asign) store write parentheses in three-step non-atomicity.

(3) synchronized you can guarantee that at the same time, only one thread can execute a method or a block of code. Includes two features: Mutex and visibility. synchronous synchronized not only resolves a thread to see that the object is in an inconsistent state, but also ensures that every thread that enters the synchronization method or synchronizes the code block sees all the modifications before being protected by the same lock.

3. Inter- thread communication

3.1 implementation of the wait notification mechanism

(1) Wait ()/notify ()/notifyall () are all methods of the object class. You need to obtain an object lock before calling these methods. The thread that calls the wait () method will stop at that line of code and release the lock, and the "pre-execution queue" is awakened before the opportunity to acquire the lock. The thread that executes the Notify () method does not release the lock, and randomly wakes up a thread that is waiting for "shared resources," which is ignored if the thread of a blocked shared resource is not. Notifyall () wakes up all, waits for this thread to exit the CPU, these threads go scramble for the lock.

(2) Each lock object has two queues, one is a ready queue (operational), and one is a blocking queue (which is run after wake-up).

(3) The Sleep method does not release the lock. A lock is released when an exception is encountered.

(4) Wait (long) waits long, and automatically wakes up if there are no other threads to wake it. When you use wait and notify, be aware that the wait condition changes, which can easily cause procedural logic confusion.

(5) Producer, consumer mode realization: The value of the producer is not empty, then lock.wait (); otherwise set the value of the operation, and then Lock.notify () wake the consumer. The value of the consumer is null, then lock.wait (), otherwise the operation is taken, and then lock.notify () wakes the producer.

Multi-production-single consumption: Using Notify will cause suspended animation, using Notifyall to solve.

(6) Through the pipeline flow for inter-thread communication, Pipedinputstream,pipedoutputstream,pipedreader and PipedWriter. Last Outputstream.connect (InputStream)

3.2 use of method join

(1) The method join is the task that causes the owning thread object x to execute the Run method, and causes the current thread Z to block indefinitely, waiting for the thread to destroy after continuing with the code behind Z. The exception occurs during the join process if the current thread is interrupted.

(2) Join (long) is implemented using wait, so the lock is released. But sleep does not.

3.3 use of Class threadlocal

(1) This class solves the problem that each thread has its own shared variable.

ThreadLocal t=new ThreadLocal (); This object has a get (), set () method. The solution is the isolation of variables between different threads. That is, different threads can have their own values and are stored in threadlocal.

(2) The Inheritablethreadlocal class, which can get the values inherited by the parent thread in the child thread.

4.Lock the Use

The 4.1 Reentrantlock class is designed to achieve synchronous asynchrony and is more flexible than synchronized.

(1) First lock lock =new reentrantlock (); Then the first line in the method that needs to be synchronized uses Lock.lock (), and the end line of the method uses Lock.unlock (). The effect is the same as using the Synchronized keyword. Of course, you can also lock part of the code block.

(2) The condition object implements the wait, notification for the specified thread, equivalent to wait and notify upgrades. Synchronized is equivalent to only one condition object.

First lock lock =new reentrantlock ();

Condition condition=new Condition ();

Call Lock.lock () in the method first to get the synchronization monitor (otherwise report an exception) and then use Condition.await () to get the thread into the blocking queue.

(3) Use condition to implement wait notifications

Conditiona.await () enters the block, conditiona.signal () wakes up the specified thread.

Signalall () is equivalent to Notifyall.

(4) Using multiple condition implementations to notify part of a thread

Condition conditiona=new Condition ();

Condition conditionb=new Condition ();

Conditiona.await () only conditiona.signal (all) can wake up

(5) Producer Consumer Models, Lock.lock () and Signall methods can also be implemented.

(6) Fair Lock: The order in which threads are acquired is assigned in the order of line Cheng, first come first served. Non-fair lock, using preemption mechanism, randomly acquire the lock. The Reentranlock class uses a non-fair lock by default.

(7) int Getholdcount () returns the number of times the current thread has called the Lock () method.

(8) int getqueuelength () returns the estimated number of threads that are waiting to get this lock.

(9) Int getwaitqueuelength (Condition Condition) returns the thread estimate of Condition for a given condition that is related to this lock.

Boolean hasqueuedthread (thread) query specifies whether the thread is waiting for this lock,

The Haswaiters Method Boolean (Condition Condition) function is to query whether a thread is waiting for the Condition condition associated with this lock.

(11) Multiple condition objects can be used to implement the order of the business. Alternating link wakeup.

A method conditiona.await ()---conditionb.signalall--

Conditionb.await ()---conditionc.signalall--in the B method

C method conditionc.await ()---conditiona.signalall--

4.2ReentrantReadWriteLock class

Read locks are shared locks, write locks are exclusive locks, read-read shares are asynchronous, write-read, write-write are mutually exclusive synchronization.

(1) Read-read sharing for Reentrantreadwritelock class

Reentrantreadwritelock lock=new Reentrantreadwritelock ();

Lock.readlock (). Lock ();

...... Code snippet

Lock.readlock (). Unlock ()

is asynchronous.

(2) Reentrantreadwritelock class implements write mutex

Reentrantreadwritelock lock=new Reentrantreadwritelock ();

Lock. Writelock (). Lock ();

...... Code snippet

Lock. Writelock (). Unlock ()

It's synchronous.

(3) Reentrantreadwritelock class implements read-write mutex

Reentrantreadwritelock lock=new Reentrantreadwritelock ();

Method 1

Lock.readlock (). Lock ();

...... Code snippet

Lock.readlock (). Unlock ()

Method 2

Lock. Writelock (). Lock ();

...... Code snippet

Lock. Writelock (). Unlock ()

The two methods are mutually exclusive.

5. Single Case mode and multithreading

(1) Load now/a hungry man mode

Immediate loading is when the object is created using the class, and the common implementation is the new instantiation.

public class myobject{

private static MyObject myobject=new MyObject ();

Private MyObject () {

}

public static MyObject getinstance () {

Return MyObject

}

}

(2) Lazy loading/lazy mode

The instance is created when the getinstance () method is called, and the object is instantiated in the method.

public class myobject{

private static MyObject MyObject;

Private MyObject () {

}

public static MyObject getinstance () {

if (myobject!=null) {

}else{

Myobject=new MyObject ();

}

Return MyObject

}

}

Lazy mode is prone to error in multi-threaded environments and cannot be maintained in single cases.

Solution:

1. method declaration synchronized-but inefficient

2. Synchronous code block-(all methods) inefficient, (key statement) cannot be singleton.

3. Synchronous code block, using DCL double detection, most of this way. That is to say in the internal key method to judge again.

public class myobject{

Valotile private static MyObject MyObject;

public static MyObject getinstance () {

if (myobject!=null) {

}else{

Thread.Sleep (3000);

Synchronized (Myobject.class) {

If (myobject==null) {

Myobject=new MyObject ();

}

}

}

Return MyObject

}

}

4.static code block for single-case mode

A feature that uses static blocks of code that have been implemented when using classes.

The core technical summary of multithreaded programming (read Zhou Zhiming book summary)

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.