Java Multithreading Core technology comb (with source code)

Source: Internet
Author: User
Tags deprecated garbage collection instance method mutex thread class visibility volatile git clone
Java Multithreading Core technology comb (with source code)

Java Multithreading Core Technology comb the source code written in front Java multithreaded objects and variables concurrent access between threads communication lock usage Timer single case mode and multithreading supplementary reference

This paper combs the basics of multithreading, including the basic use of multithreading, the concurrent access of objects and variables, the communication between threads, the use of lock, timer, single case mode, and thread state and thread group. It 's written in front .

Spent a week reading "Java Multithreaded Programming Core technology" (Gaohong), this article is the collation of the book, almost all the examples, I have personally knocked, and uploaded to my github, interested friends can go to my github download. The source code uses MAVEN constructs, the multithreading this part source code is located in the Java-multithread module. Warehouse Address: java-learning git clone:git@github.com:brianway/java-learning.git java multithreading

The

Basic knowledge creates threads in two ways: 1. Inherit thread class, 2. Implement Runnable interface. The specific two links can refer to my previous blog post "Java Foundation Consolidation Notes (5)-Multi-line threads traditional multithreading" some basic api:isalive (), Sleep (), getId (), yield () and so on.
IsAlive () tests whether the thread is active sleep () let the "executing thread" hibernate getId () get the thread unique identity yield () discard the current CPU resource deprecated api:stop (), suspend (), resume (), and so on, has been deprecated because of problems such as the possibility of data being out of sync. Several ways to stop a thread:
Use exit identification to cause the thread to exit normally, that is, the Run method completes. Use the priority of thread threads in the Interrupt method: inheritance, regularity, randomness
The thread's precedence is inherited. If thread A starts thread B, the priority of the thread is the same as the B and a priority. The CPU tends to be as random as possible to prioritize thread threads with higher resource priorities. Precedence is not the same as the order of execution, and the relationship is uncertain between two threads in Java: The user thread and the daemon (Daemon) thread.
Daemon Thread: When a non-daemon thread does not exist in the process, the daemon automatically destroys it. Typical examples are: garbage collection threads.

Compare and discriminate between a thread and the current thread: The current thread refers to the running thread, which can be determined by the CurrentThread () method return value. For example, if you call the Run method directly in the main method, and the start method of the calling thread, the current thread result is printed differently. The interrupted () and isinterrupted ()
interrupted () are static methods of the class that test the ability to clear the status flag to False when the thread is already in an interrupted state. Isinterrupted () is an instance method of a class that tests whether the thread object is already in an interrupted state, but does not know the status flag. The difference between sleep () and wait () is that
Morpheus () is a static (static) method of the thread class; the wait () method is a method in the object class that retains the lock of the object while it sleeps (), and still holds the lock; free object locks when you sleep After the sleep () hibernation time expires, the thread does not necessarily execute immediately, because other threads may be running and are not scheduled to abort execution unless the thread has a higher priority; wait () Use notify or notifyalll or specify sleep time to wake up threads in the current waiting pool wait () must be placed in the synchronized block. Otherwise, the java.lang.IllegalMonitorStateException exception will be thrown out at runtime

Method whether to release the lock Notes
Wait Is Wait and Notify/notifyall appear in pairs and must be called in the Synchronize block
Sleep Whether Enables lower-priority threads to get execution opportunities
Yield Whether The yield method gives the current thread the CPU possession, but the time to yield is not set
concurrent access to objects and variablesSynchronized keyword
The method that invokes the keyword synchronized declaration is queued. However, if thread a holds a lock on an object, then thread B asynchronously invokes a synchronized type of method without restriction. Synchronized lock reentry: When a thread gets an object lock, it can get a lock on the object when it is requested to lock again. Also, subclasses can invoke the synchronization method of the parent class through a "reentrant lock". Synchronization does not have inheritance. Synchronized uses a "object monitor" that must be the same object synchronized synchronization method and synchronized synchronized code block.
Calls to other synchronized synchronization methods or code blocks are blocked. At the same time only one thread can execute the code synchronized (not the This object x) in the Synchronized Method/code block, and the X object as the object monitor
Synchronization effect when multiple threads execute synchronized (x) {} synchronized code block when other threads perform a synchronization effect when the Synchronizd synchronization method in the X object is synchronized when other threads execute the synchronized (this) code block in the X object method The static synchronization synchronized method and the synchronized (class) code block: Holding the lock on the current corresponding class class.

Private stack diagram of threads

Volatile keyword: The primary role is to make a variable visible between multiple threads ... The volatile keyword can be enforced from the public stack rather than taking the value of the variable from the thread private data stack
Setting the state bit in the while loop in the method (without the volatile keyword), it is not feasible to place the state position on the outside, the loop does not stop, such as the JVM in-server mode. Reason: The values in the private stack and the values in the public stack are different steps volatile increases the visibility of instance variables across multiple threads, but does not support atomic atomic classes: An atomic type is a type that is available for atomic operations and can be thread safe without locks. But atomic classes are not completely secure, and although atomic operations are safe, the calls between methods are not atomic and need to be synchronized.

Reading public Memory graphs

Discrimination and piecemeal complementary synchronized static methods and Non-static methods: Synchronized keyword plus static method is to lock class class, you can work on all instance objects of the class The Synchronized keyword is added to the non-static static method to lock the object and work on the object. These two locks are not the same lock. Comparison of synchronized and volatile
1 keyword volatile is a lightweight implementation of thread synchronization, performance is better than synchronized, and volatile can only modify variables, synchronized can modify methods and code blocks. 2 multithreading access volatile will not be blocked, synchronized will appear blocking 3) volatile can guarantee the visibility of data, not guarantee atomicity, synchronized can guarantee atomicity, but also can indirectly guarantee visibility, because Synchronized will synchronize the private memory with the data in public memory . 4 volatile resolves the visibility of variables across multiple threads, synchronized solves the synchronization of multiple threads accessing resources. string constant pool attribute, so in most cases the synchronized code block does not apply string as the lock object. Multithreading deadlock. Using the JDK self-contained tool, the JPS Command +jstack command to monitor for deadlocks. Built-in classes and static built-in classes. The change of the lock object. When an exception occurs for a thread, its held locks are automatically freed.

Diagram of the working process of variables in memory

Communication between ThreadsWaiting/notification mechanism: Wait () and notify ()/notifyall (). Wait causes the thread to stop running, notify to keep the stopped thread running.
Wait (): Waits on the thread of the current executing code, placing it in the pre-execution queue.
The thread must obtain an object-level lock on the object before calling Wait (), the current thread immediately releases the lock after the Wait () method is executed, and the thread competes with other threads to regain the lock before the wait () is returned, when the thread is in the wait () state, the calling thread's Interrup method, the Interrupedexception exception Wait (long) is waiting for a thread to wake the lock during a certain time, and the timeout automatically wakes up. Notify (): Notifies other threads that may wait for an object lock on the object. Randomly select a wait-state thread so that it waits for an object lock to get the object.
Before calling notify (), the thread must obtain an object-level lock on the object, and the lock will not be released immediately after the Notify () method is executed, and the current thread will not release the lock until the synchronized code block is exited. Notify () only random notification at a timeaThe thread wakes up Notifyall () and notify () almost, except that all threads waiting in the queue for the same shared resource are exited from the wait state and into the operational state. Each lock object has two queues: a ready queue and a blocking queue.
Ready queues: Storing threads blocking queues for locks: storing blocked thread producer/consumer mode
"Suspended animation": Thread into the waiting waiting state, the process of suspended animation, all threads are waiting state.
The main reason for suspended animation: it is possible to awaken the same kind continuously. Notify awakening is not necessarily an anomaly, perhaps the same as "producer" Awakens "producer". Solve the death of death: Change Notify () to Notifyall () wait condition changes, there may be an exception, you need to change the if to a while through the pipeline communication between threads: one thread sends data to the output pipe, another thread reads the data from the input pipe.
BYTE streams: PipedInputStream and PipedOutputStream character streams: Pipedreader and PipedWriter join (): Wait for the thread object to be destroyed and have the function of queuing the thread.
The join () and interrupt () methods encounter an exception. Join (long) sets the difference between a waiting time join and a synchronized: The join uses the Wait () method internally for waiting; Synchronized uses the object monitor principle as a synchronous join (long) and sleep ( Long): The join (long) is implemented using a wait (long), so the join (long) has the characteristic of releasing the lock; Thread.Sleep (long) does not release the lock. Threadlocal class: Each thread binds its own value
The InitialValue () method of the overridden class can initialize the variable to solve the problem where get () returns null Inheritablethreadlocal class can take the value inherited by the parent thread in the child thread.Use of lockReentrantlock class: Implement synchronous mutex between threads, more flexible than synchronized
Lock (), the invoked thread holds the object monitor, and the effect is the same as synchronized using the condition implementation wait/notify: more flexible than Waiting () and notify ()/notyfyall (), for example, multiple notifications can be implemented.
Call Lock.lock () to get sync Monitor before calling condition.await ()

Comparison between object and condition method

Object Condition
Wait () Await ()
Wait (long timeout) Await (long time,timeunit unit)
Notify () Signal ()
Notifyall () Signalall ()

Some APIs

Method Description
int Getholdcount () The number of times the lock () method is invoked by querying the current thread for the number of locks held
int Getqueuelength () Returns the number of thread estimates that are waiting to get this lock
int Getwaitqueuelength (Condition Condition) Returns the number of thread estimates waiting for a given condition Conditon associated with this lock
Boolean hasqueuethread (thread thread) Query whether the specified thread is waiting to get this lock
Boolean hasqueuethreads () Query if threads are waiting to get this lock
Boolean haswaiters (Condition) Query whether threads are waiting for the condition condition associated with this lock
Boolean Isfair () Judge is not a fair lock
Boolean Isheldbycurrentthread () Query whether the current thread maintains this lock
Boolean islocked () Query whether this lock is persisted by any thread
void lockinterruptibly () Gets the lock if the current thread is not interrupted and an exception occurs if it has been interrupted
Boolean Trylock () Gets the lock only if it is not persisted by another thread at the time of the call
Boolean Trylock (Long timeout,timeunit unit) Gets the lock if it is not persisted by another thread for a given wait time, and the current thread is not interrupted
Fair lock and non-fair lock
A fair lock indicates that the order in which the thread acquires the lock is assigned in the order of lock, that is, FIFO first out. The non-fair lock is a preemption mechanism to acquire locks and acquire locks randomly. Reentrantreadwritelock class
Read-Share write-write mutual exclusion read-write Mutex Timer

Common APIs

Method Description
Schedule (timertask task, Date time) Perform a task on a specified date
Scheduleatfixedrate (timertask task, Date Firsttime, long period) Performs a task in an infinite loop after a specified date, at the specified interval period
Schedule (timertask task, long delay) To perform a timertask task after the specified number of milliseconds is deferred after the current time for this method is the reference time.
Schedule (timertask task, long delay, long period) The current time to execute this method is the reference time, based on which the specified number of milliseconds is deferred, and a TimerTask task is performed at an infinite number of intervals.
The difference between schedule and scheduleatfixedrate: Schedule does not have the pursuit of execution; Scheduleatfixedrate has the pursuit of execution. single case mode and multithreadingLoad Now/"A Hungry Man mode": the instance has been created before the method is invoked. Deferred load/"lazy mode" implemented through the static property new instantiation: the instance is created when the Get () method is invoked. The most common implementation is the new instantiation in the Get () method
Disadvantage: In a multithreaded environment, there will be a problem solving method
Declare synchronized keyword, but run very low efficiency synchronous code block, efficiency is also low for some important code (instantiation statements) alone synchronization, efficiency, but there will be problems using the Enum enumeration data type to implement Singleton mode with DCL double check lock Supplementary Supplements

Schematic diagram of method and state relation

Status of the thread: Thread.state enumeration class, refer to official website apienum thread.state thread Group: Thread groups can be wired or threaded, and threads can be wired in groups. You can manage threads or thread group objects in bulk. SimpleDateFormat is not thread safe, and the solution is:
Creating instances of multiple SimpleDateFormat classes using the Threadlocal class thread group for exception handling
Setuncaughtexceptionhandler () Sets the exception handler for the specified thread alignment Setdefaultuncaughtexceptionhandler () Set exception handler reference for all thread objects On the usage of lock Java synchronized keyword in Java Java thread (threading) Case details the difference between sleep and wait

Author @brianway More articles: personal website | CSDN | Oschina

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.