The following is my study of multi-threaded records of knowledge points, and did not elaborate on each knowledge point, just the important knowledge points recorded down, there is time to see, if there is not the place, welcome to spend, thank you!
1, multi-threaded status and creation method:
The state of the thread:
1. New state: The thread object has been created and the start () method has not been invoked on it.
2. Operational status: When the thread is eligible to run, but the scheduler has not selected it as the state in which the thread is running. When the start () method is called, the thread first enters the operational state. After the thread has run or has returned from blocking, waiting, or sleeping, it returns to the operational state.
3. Running state: The thread Scheduler selects a thread from a running pool as the current thread is in the state of the thread. This is also the only way that a thread goes into a running state.
4. Wait/block/Sleep state: This is the state at which the thread is eligible to run. In fact, this three-state combination is one, and its common denominator is that the thread is still alive, but there is no condition to run at the moment. In other words, it is operational, but if an event occurs, he may return to the operational state.
5. Death state: When the thread's run () method finishes, it is considered dead. This thread object may be alive, but it is not a separate thread. Once a thread dies, it cannot be resurrected. If you call the start () method on a dead thread, the java.lang.IllegalThreadStateException exception is thrown.
2 Ways to create threads:
Inheriting the thread class and implementing the Runnable interface class, creating a thread instance requires passing an instance of an interface implementation class to the thread constructor when the interface is implemented in a way that implements it. Because Java does not support multiple inheritance, it is recommended that threads be created in a way that implements the Runnable interface.
2, thread synchronization, Keywords: synchronized and volatile, and their differences. Why the deadlock occurred
The allocation of memory according to the JVM running time. One of the memory areas is the JVM virtual machine stack, each thread runs with a line stacks, and the line stacks saves the thread runtime variable value information. When a thread accesses an object, the value of the variable that corresponds to the heap memory is found first through the object's reference, then the concrete value of the heap memory variable is load into the thread local memory, a copy of the variable is created, and then the thread is no longer related to the object's value in the heap memory variable, but instead directly modifies the value of the At some point after the modification (before the thread exits), the value of the thread variable copy is automatically written back to the object in the heap variable. This changes the value of the object in the heap. So variables that are shared across multiple threads can have problems.
When a shared variable is modified by volatile, it guarantees that the modified value is immediately updated to main memory, and when other threads need to read it, it will read the new value in RAM. So sometimes it is possible to prevent a thread from reading a shared variable when the value is incorrect, but volatile does not guarantee the atomicity of the variable, and if the shared variable is a simple data type, the modification of the variable is not based on its own value (e.g. x=10 can, X + + does not), can guarantee its atomicity. Because volatile does not guarantee atomicity, it is prudent to use volatile. Here is just a simple note, about Bolatitle more detailed introduction can look at the following article:
Http://www.cnblogs.com/dolphin0520/p/3920373.html#commentform
http://www.infoq.com/cn/articles/java-memory-model-4/
http://blog.csdn.net/hupitao/article/details/45227891
Http://www.cnblogs.com/aigongsi/archive/2012/04/01/2429166.html
Synchronized Knowledge Points:
When synchronized modifies a method, the method is called a synchronous method, and if synchronized acts on a block of code, the Code library is called a synchronous code block.
Java object locks and class Locks: Java's object locks and class locks are basically consistent with the built-in locks in terms of locks, however, two locks are actually very different, object locks are used for object instance methods, or on an object instance, class locks are used for static methods of classes or for class objects on classes. We know that there can be many object instances of a class, but each class has only one class object, so object locks for different object instances do not interfere with each other, but each class has only one class lock. One thing to note, though, is that a class lock is just a conceptual thing, not a real one, it's just a way to help us understand the difference between a locked instance method and a static method.
Synchronized block notation:
Synchronized (object) {...}
Indicates that the thread will lock the object when executing (note that the object can be an object of any class or use the This keyword). This allows you to set your own lock object.
If the synchronized in the synchronization code block is a class object (such as Object.class), the method that represents the class is locked
A non-static synchronization method locks an object, but the lock of a static method does not belong to the object, and when a synchronized keyword-modified method is also modified by static, its lock belongs to the class, which locks the class object of the classes in which the method resides.
Class and object locks are two distinct locks that control different areas and do not interfere with each other. Similarly, when a thread obtains an object lock, it can also get the lock, which is allowed by acquiring two locks at the same time.
If an object has more than one synchronized method (including a synchronous block of code), a thread has entered a synchronized method (including a synchronous block of code) at some point, and before the method has finished executing, Other threads are not able to access any of the synchronized methods of the object (including synchronous code blocks). However, you can access non-synchronous methods and non-synchronized code blocks.
For the usage of sychronized, take a look at the following article:
http://zhh9106.iteye.com/blog/2151791
Http://www.cnblogs.com/GnagWang/archive/2011/02/27/1966606.html
Http://www.cnblogs.com/mengdd/archive/2013/02/16/2913806.html
The Synchronized keyword is to prevent multiple threads from executing a piece of code at the same time, which can affect program execution efficiency, while the volatile keyword has better performance than synchronized in some cases. Note, however, that the volatile keyword cannot replace the synchronized keyword because the volatile keyword does not guarantee the atomicity of the operation.
3. Communication between threads, common methods: Wait, notify, Notifyall, join, Yeild
Wait (), notify (), and Notifyall () are methods in the object class and cannot be overridden to look at the JDK source code;
The wait and notify, Notifyall methods must be used in conjunction with synchronized;
Wait releases the lock, noting that if sleep is used in a synchronous method or block of code, sleep causes the thread to hibernate, but sleep does not release the lock;
If only one thread is waiting, it is better to use notify because it is more efficient than notify. If you are unsure whether to use the Notify or the Notifyall method, you might be using Notifyall, which may be a waste of resources, but more secure. The Notify method wakes only one thread in the wait (this thread is determined by the JVM, it is not specific, it is random, Regardless of the thread priority).
Note that when calling notify and Nofityall, it is not possible to wake the thread of a waiting state exactly, but the JVM determines which thread to wake and is not prioritized by the thread.
Note the notify of missing notifications and early notifications, the following code appears in the typical synchronization code: if (condition) {wait ()}, where there is a risk of missing notifications, you can change if to while to avoid such problems.
Threads can use classes Threadlocal and inheritablethreadlocal to let specific thread variables be different values in different threads
The join () method is basically to get the thread that called the method to complete the code inside the Run method after executing the join () method, for example: You and friends go to dinner, halfway you have something, your friend even eat full, will be there waiting for you, because he did not bring money to come back with you after the checkout to go together.
The join method can be called only in threads that inherit the thread class
The thread must have start () before the join will work
The Thread.yield () method acts by suspending the currently executing thread object and executing other threads.
Yield () should be done to get the current running thread back to the operational state to allow other threads with the same priority to get the run opportunity. Therefore, the purpose of using yield () is to allow appropriate rotation between threads of the same priority. However, in practice there is no guarantee that yield () will be compromised, as the thread of the concession may be checked again by the thread scheduler.
Conclusion: Yield () never causes the thread to go to the wait/sleep/block state. In most cases, yield () will cause the thread to go from the running state to the operational state, but it may not be effective.
You can look at the following articles:
Http://www.cnblogs.com/riskyer/p/3263032.html
4. Daemon thread and Thread priority
1. What is a daemon thread (daemon thread)?
A daemon is a thread that runs in the background, in contrast to a user thread. When a running thread is a daemon thread, the Java virtual machine exits. Regardless of whether the daemon thread executes or not, it exits directly, which is especially important. When a user thread exists that the user thread is running, the daemon thread will also run.
2. How do I create a daemon thread?
Create a new thread with the Setdaemon (Boolean on) method to conveniently set the thread's daemon mode, true to daemon mode, and false to user mode. The Setdaemon (Boolean on) method must be called before the thread is started, and an exception is generated when threads are running. The Isdaemon method tests whether the thread is a daemon thread. It is worth mentioning that when you create other threads in a daemon thread, these newly generated threads do not have to set the Daemon property, they will be the daemon thread, and the user thread is the same.
3. What is the use of daemon threads?
Daemon threads use less, but are not useless, for example, the JVM's garbage collection, memory management, and other threads are daemon threads. There is in the database application, the use of the database connection pool, the connection pool itself contains a lot of background threads, monitoring the number of connections, time-out, status, and so on. A daemon thread is typically serviced by a user thread.
You can look at the following articles:
http://blog.csdn.net/ljyy2006/article/details/1901109
http://lavasoft.blog.51cto.com/62575/221845/
Http://www.cnblogs.com/super-d2/p/3348183.html
Thread Priority:
The thread's priority still does not guarantee the thread's execution order. However, high-priority threads have a higher probability of getting CPU resources, and the lower priority is not a chance to execute.
When designing multithreaded applications, be sure not to rely on the priority of the thread. Because thread scheduling priority operations are not guaranteed, thread precedence can only be used as a way to improve program efficiency, but ensure that the program does not rely on such operations.
The priority of a thread is expressed as an integer between 1-10, and the higher the value, the higher the priority is, and the default priority is 5.
When another new thread is opened in one thread, the new one is called the thread's child thread, and the child thread has the same initial priority as the parent thread.
If the thread already belongs to a thread group (threadgroup), the thread's priority cannot exceed the priority of the thread group
5, thread groups, threads pool
Java provides the Threadgroup class to control a thread group, a thread group can be created by thread objects, can be created by other lines Cheng, a tree-structured thread is generated, and thread grouping is an interesting feature provided by the Java Concurrency API. We can treat a set of threads as a standalone unit and manipulate thread objects in the thread group at will. For example, you can control a set of threads to run the same tasks without caring how many of them are still running, and you can interrupt execution of all threads with one interrupt call.
Java provides the Threadgroup class to control a thread group. A thread group can be created from a thread object, or it can be created by another line Cheng, generating a tree-structured thread. It is no longer recommended to use Threadgroup, as described in effective Java. It is recommended to use executor.
The threads created by default in Java are all part of the system thread group, and the threads of the same thread group can modify each other's data. However, if you are in a different thread group, you cannot modify the data across thread groups to ensure data security to some extent.
1. Why a thread pool is needed
Network requests usually have two forms: the first, the request is not very frequent, and each connection will remain for a considerable period of time to read data or write data, and finally disconnected, such as file download, network streaming media. Another form is frequent requests, but the connection is disconnected after a small amount of data is read/written. Given the concurrency of the service, if each request comes in after the service starts a thread for it, the resources for the service can be wasteful, especially in the second case. Because it is usually time-consuming to create a thread, set this time to T1, and after the read/write service is T2, when t1>>t2, we should consider a strategy or mechanism to control, so that the service for the second way of request can be done at a lower power consumption.
In general, we can use the thread pool to solve this problem, first of all, when the service starts, we can start several threads and use a container (such as a thread pool) to manage these threads. When the request arrives, you can go from the pool to a thread, perform the task (usually a response to the request), and then put the thread back in the pool when the task ends, and if the request arrives and there are no idle threads in the pool, the request needs to be queued. Finally, the pool is destroyed when the service shuts down.
The JDK provides a thread pool, and within the Java.util.concurrent package, you can see the JDK's implementation of the thread pool, and the following articles about the thread pool can look at:
http://www.oschina.net/question/565065_86540
Http://www.cnblogs.com/dolphin0520/p/3932921.html
6, using the pipeline between the flow of data between threads
Java provides a variety of input and output streams, which enable programmers to easily manipulate data. Where pipe flow is a special flow that transmits data directly between different threads. One thread sends the data to the output pipeline, and the other thread reads the data from the input pipeline. By using pipelines, you achieve the purpose of communicating between multiple threads. So, how do you create and use pipelines?
Java provides two special classes specifically designed to handle pipelines, which are the PipedInputStream class and the PipedOutputStream class.
Where PipedInputStream represents the output of the data in the pipeline, that is, the thread reads one end of the data from the pipe, and PipedOutputStream represents the input of the data in the pipeline, which is the end of the thread writing to the pipe, These two classes can be used together to create a pipe flow object for data input and output.
Once the pipeline is created, it is possible to use multi-threaded communication mechanism to read and write the data through the pipeline, so that multi-threaded programming plays a more important role in practical application.
You can look at the following articles:
Http://www.zhujiangroad.com/program/JAVA/1942.html
7. Why stop, suspend, resume method is eliminated, and how to implement similar behavior safely
The suspend () method is to suspend (pause) a thread, and the resume () method is to continue the execution of a pending line Cheng.
Suspend () and resume () methods: Two methods are used, suspend () causes the thread to enter a blocking state, and does not automatically recover, it must be called by its corresponding resume () to enable the thread to re-enter the executable state. Typically, suspend () and resume () are used when waiting for the result of another thread: After the test finds that the result has not yet been generated, the thread is blocked and the other thread produces the result, calling resume () to restore it. If the method thread calling suspend tries to get the same lock, the program will deadlock.
The most prudent approach is to have the target thread poll for a variable that indicates the desired thread state (active or suspended). When a pending state is required, the thread waits with object.wait. When the thread resumes, the target thread is notified using Object.notify.
Stop this method terminates all methods that are not closed, including the Run method. When a thread stops, he immediately releases all locks on the object he locks. This causes the object to be in an inconsistent state. If a method transfers money from one account to another, it stops before the deposit is made. Now the bank object is destroyed. Because the lock has been released. When a thread wants to terminate another thread, it cannot know when it is safe to call stop and when it will cause the object to be destroyed. So this method is deprecated. You should interrupt a thread instead of stopping him. We usually use the Windows system, a program will appear unresponsive, at this time in the Task Manager directly terminate the process, like a similar situation, you can use the stop directly.
Most situations that use stop should be replaced with code that simply modifies some variables to indicate that the target thread should stop running. The target thread should check the variable periodically and return it in a reasonable way from its run method when it indicates that it needs to stop running (this is the method that the JavaSoft tutorial always recommends). To ensure that the requested instant traffic is stopped, the variable must be volatile (or access to the variable must be synchronous).
You can look at the following articles:
http://blog.csdn.net/linchengzhi/article/details/7468395
http://blog.163.com/feng_welcome/blog/static/17177032420112246191360/
8. Interrupt method: "Perfect Termination thread"
The Thread.Interrupt () method does not break a running thread. This approach is actually done by throwing an interrupt signal when the thread is blocked, so that the threads can exit the blocked state. Rather, if the thread is blocked by one of the three methods of Object.wait, Thread.Join, and Thread.Sleep, it will receive an interrupt exception (interruptedexception), thus terminating the blocked state early.
Therefore, if a thread is blocked by several of these methods, the correct way to stop the thread is to set the shared variable and call interrupt () (note that the variable should be set first). If the thread is not blocked, calling interrupt () will not work, otherwise the thread will get an exception (the thread must be prepared to handle the condition beforehand) and then flee the blocking state. In either case, the last thread checks the shared variable and then stops.
9. Deadlock
1. Cause of deadlock
Java thread deadlock is a classic multithreading problem because different threads are waiting for locks that are simply not possible to be released, causing all work to fail. Suppose there are two threads, representing two hungry people, who must share a knife and fork and take turns to eat. They all need to get two locks: a lock with a shared knife and a shared fork. If thread "a" gets a knife, and thread "B" gets a fork. Thread "A" will go into a blocking state to wait for a fork, while thread "B" blocks to wait for a knife owned by "a".
The root cause of deadlocks is the inappropriate use of the "synchronized" keyword to manage thread access to specific objects
A common rule of thumb for avoiding deadlocks is that when several threads have access to shared resources A, B, and C, make sure that each thread accesses them in the same order, such as first accessing a, and accessing B and C.
You can look at the following articles:
http://leowzy.iteye.com/blog/740859
2. View Thread deadlock
Http://www.cnblogs.com/ilahsa/archive/2013/06/03/3115410.html
10, self-running activity-like technology, recommended to use the anonymous inner class to hide the design of the Run method
Self-running Activity class technology: Starts a thread in the thread subclass or in a constructor in the implementation runnable interface class;
Hide the design of the Run method: use anonymous inner classes to create threads within normal class construction methods, and then start threads
Java Multithreading Knowledge points