Java multithreading knowledge point, java Multithreading

Source: Internet
Author: User

Java multithreading knowledge point, java Multithreading

The following is my knowledge point on multi-thread recording. I didn't explain each knowledge point in detail. I just recorded the important knowledge points. If you have time, you can check them out. If there is something wrong, you are welcome to pay. Thank you!

1. multithreading status and creation method:
Thread status:
1. New State: the thread object has been created and the start () method has not been called on it.
2. Run Status: When the thread is eligible to run, but the scheduler has not selected it as the status of the thread when it is running. When the start () method is called, the thread first enters the runable state. After the thread is running or after it is returned from the blocking, waiting, or sleep status, it also returns to the runable status.
3. Running status: the thread scheduler selects a thread from the runable pool as the status of the current thread. This is the only way for a thread to enter the running state.
4. Waiting/blocking/sleep status: this is the status where the thread is eligible to run. In fact, the three States are combined into one. The common feature is that the thread is still active, but there are currently no conditions to run. In other words, it is runable, but if an event appears, it may return to the runable status.
5. Dead state: When the thread's run () method is completed, it is considered dead. This thread object may be active, but it is no longer a separate thread. Once a thread dies, it cannot be resumed. If the start () method is called on a dead thread, a java. lang. IllegalThreadStateException is thrown.
Two ways to create a thread:

Inherit the Thread class and implement the Runnable interface class. When using the method of implementing the interface, you must pass the instance of the interface implementation class to the Thread constructor to create a Thread instance. Because java does not support multi-inheritance, we recommend using the runnable interface to create threads.


2. Thread Synchronization. Keyword: synchronized and volatile.

Volatile knowledge points:

  • Memory Allocation Based on the jvm runtime. One of the memory areas is the jvm Virtual Machine stack. Each thread has a thread stack during running, and the thread stack stores the variable value information during running. When the thread accesses a value of an object, it first finds the value of the variable corresponding to the heap memory through the object reference, load the specific value of the heap memory variable to the local memory of the thread and create a copy of the variable. Then, the thread no longer has any relationship with the variable value of the object in the heap memory, instead, the value of the copy variable is directly modified. At a certain time point after modification (before the thread exits), the value of the copy of the thread variable is automatically written back to the object's heap variable. In this way, the value of the object in the heap changes. Therefore, variables shared by multiple threads may have problems.
  • When a shared variable is modified by volatile, it ensures that the modified value is immediately updated to the primary storage. When other threads need to read the variable, it reads the new value from the memory. So sometimes the value of shared variables cannot be read correctly by the thread, but volatile cannot guarantee the atomicity of the variables. If the shared variables are of a simple data type, variable modification is not based on its own values (for example, x = 10, x ++), and can ensure its atomicity. because volatile does not guarantee atomicity, use volatile with caution. Here is just a simple note. For more details about bolatitle, you can refer to 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 point:

  • When synchronized modifies a method, this method is called a synchronous method. If synchronized acts on a code block, the code base is called a synchronous code block.
  • Java Object locks and class locks: java Object locks and class locks are basically the same as built-in locks in terms of the concept. However, there is a big difference between the two locks. Object locks are used for object instance methods or on an object instance, A class lock is used for static methods of a class or class objects of a class. We know that there can be many class object instances, but each class has only one class object, so the Object locks of different object instances do not interfere with each other, but each class has only one class lock. But it must be noted that, in fact, the class lock is only a conceptual thing, not actually exists. It is only used to help us understand the difference between the locking instance method and the static method.
  • Synchronized block Syntax: synchronized (object ){...} indicates that the thread locks the object during execution (note that this object can be any class object or use this keyword ). In this way, you can define the Lock Object on your own.
  • If the synchronized in the synchronous code block contains class objects (such as Object. class), the method of the class is locked.
  • The non-static synchronization method locks the object, but the lock of the static method does not belong to the object. When a method modified by the synchronized keyword is also modified by the static method, its lock belongs to the class, it locks the Class Object of the Class to which this method belongs.
  • The class lock and object lock are two different locks that control different regions and they do not interfere with each other. Similarly, when a thread acquires an object lock, it can also obtain this type of lock, that is, it obtains two locks at the same time, which is allowed.
  • If an object has multiple synchronized methods (including Synchronous Code blocks) and a thread enters a synchronized method (including Synchronous Code blocks) at a certain time point, before the method is executed, its threads cannot access any synchronized methods of the object (including Synchronous Code blocks ). However, you can access non-synchronous methods and non-synchronous code blocks.
  • For usage of sychronized, refer to 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 prevents multiple threads from executing a piece of code at the same time, which affects the program execution efficiency. In some cases, the volatile keyword outperforms synchronized in performance, however, note that the volatile keyword cannot replace the synchronized keyword, because the volatile keyword cannot guarantee the atomicity of the operation.


3. Common Methods for inter-thread communication: wait, notify, yyall, join, and yeild

  • Wait (), Policy (), and policyall () are methods in the Object class and cannot be overwritten. You can view the jdk source code;
  • The wait, y, and notifyAll methods must be used with synchronized;
  • Wait will release the lock. Note that if sleep is used in the synchronization method or code block, although sleep also makes the thread sleep, sleep will not release the lock; yield will not release the lock.
  • If there is only one thread waiting, it is better to use y because it is more efficient than notify. If you are not sure whether the notify or notifyall method is used, you can choose to use notifyall, which may be a waste of resources, but is safer. the notify method only wakes up one thread in the wait state (this thread is determined by the jvm and cannot be determined. It is random and has nothing to do with the thread priority ).
  • Note that when calling notify and nofityAll, you cannot exactly wake up a waiting thread. Instead, the JVM determines which thread to wake up, rather than the thread priority.
  • Pay attention to the issues caused by missing notifications and early notifications by notify. The following code appears in a typical synchronization code: if (condition) {wait ()..}, here, the notification is prone to omission. In this case, you can change if to while to avoid such problems.
  • Threads can use ThreadLocal and InheritableThreadLocal classes to make specific thread variables have different values in different threads.
  • The join () method is mainly used to let the thread that calls this method complete the items in the run method, and the code after executing the join () method. For example, you and your friends go to dinner, you have something to do in the middle. Even if your friend is full, he will wait for you there, because he didn't bring any money until you come back to settle the bill.
  • The join method can be called only in the Thread that inherits the Thread class.
  • The thread must start () before joining.
  • The Thread. yield () method is used to pause the currently executed Thread object and execute other threads.
  • What yield () should do is to bring the current running thread back to the runable state, so that other threads with the same priority can get the running opportunity. Therefore, yield () is used to enable proper rotation among threads with the same priority. However, in practice, yield () cannot be guaranteed to achieve the goal of concession, because the concession thread may be re-selected by the thread scheduler.
  • Conclusion: yield () never leads the thread to the waiting/sleep/blocking status. In most cases, yield () will cause the thread to go from the running state to the runable state, but it may not work.

Take a look at the following articles:
Http://www.cnblogs.com/riskyer/p/3263032.html


4. daemon thread and thread priority

  • What is a Daemon thread )?

The daemon thread is a background running thread, Which is compared with the User thread ). When all running threads are daemon threads, the Java Virtual Machine exits. Whether or not the daemon thread execution is completed or not, it is worth special attention. If the user thread already exists, the user thread will continue to run.

  • How to Create a daemon thread?

Create a new thread and use the setDaemon (boolean on) method to conveniently set the Daemon mode of the thread. true indicates the Daemon mode, and false indicates the User mode. The setDaemon (boolean on) method must be called before the thread starts. An exception occurs when the thread is running. The isDaemon method tests whether the thread is a daemon thread. It is worth mentioning that when you generate other threads in a Daemon thread, the newly generated threads do not need to set the Daemon attribute, and the user threads are the same.

  • What is the use of daemon threads?

Daemon threads are rarely used, but are not useless. For example, JVM garbage collection and memory management threads are all daemon threads. There is also the database connection pool used for database applications. The connection pool also contains many background threads to monitor the number of connections, timeout time, status, and so on. The daemon thread generally serves the user thread.
Take a 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 priority still cannot guarantee the thread execution order. However, a thread with a higher priority has a higher probability of obtaining CPU resources. A thread with a lower priority does not have the chance to execute the task.
  • When designing a multi-threaded application, do not rely on the thread priority. Because the thread scheduling priority operation is not guaranteed, the priority of the thread can only be used as a way to improve program efficiency, but ensure that the program does not rely on this operation.
  • The priority of a thread is represented by an integer between 1 and 10. The higher the value, the higher the priority. The default priority is 5.
  • When another new thread is enabled in a thread, the new thread is called the subthread of the thread. The initial priority of the subthread is the same as that of the parent thread.
  • If the thread already belongs to a thread group, the priority of the thread cannot exceed the priority of the thread group.

5. Thread groups and thread pools

  • Java provides the ThreadGroup class to control a thread group. A thread group can be created through a thread object or another thread group to generate a thread with a tree structure, grouping threads is an interesting feature provided by Java concurrent APIs. We can regard a group of threads as an independent unit and manipulate the thread objects in the thread group at will. For example, you can control a group of threads to run the same task without worrying about how many threads are still running. You can also use an interrupt call to interrupt the execution of all threads.
  • Java provides the ThreadGroup class to control a thread group. A thread group can be created through a thread object or another thread group to generate a thread with a tree structure. ThreadGroup is no longer recommended as described in objective Java. We recommend that you use Executor.
  • The threads created by java by default belong to the system thread group, and the threads in the same thread group can modify the data of the other thread. However, in different thread groups, data cannot be modified across thread groups, which ensures data security to a certain extent.
  • Why Thread Pool

There are usually two types of network requests: first, requests are not very frequent, and after each connection, the data will be read or written for a considerable period of time, and finally disconnected, such as file download, network streaming media. Another form is frequent requests, but the connection is closed when a small amount of data is read/written after the connection. Considering the concurrency of the service, if the service starts a thread after each request arrives, this may cause a great waste of service resources, especially in the second case. Generally, it takes a certain amount of time to create a thread. Set this time to T1, And the read/write service time after connection to T2. When T1> T2, we should consider a policy or mechanism to control the service so that the second request method can also be completed at low power consumption.
Generally, we can use a thread pool to solve this problem. First, when the service is started, we can start several threads and use a container (such as a thread pool) to manage these threads. When the request arrives, a thread can be taken out from the pool to execute the task (usually the response to the request). After the task ends, the thread is put into the pool for backup; if a request arrives and there is no idle thread in the pool, the request must be queued. Finally, destroy the pool when the service is closed.
Jdk provides a thread pool. In the java. util. concurrent package, you can see the implementation of the jdk thread pool. The following articles on the thread pool can be viewed:
Http://www.oschina.net/question/565065_86540
Http://www.cnblogs.com/dolphin0520/p/3932921.html


6. Use pipelines to flow data between threads

  • Java provides a variety of input and output streams, allowing programmers to conveniently operate on data. Pipeline (pipe) is a special stream used to directly transmit data between different threads. One thread sends data to the output pipeline, and the other thread reads data from the input pipeline. You can use pipelines to achieve communication between multiple threads. So how to create and use pipelines?
  • Java provides two special classes for processing pipelines. They are PipedInputStream and PipedOutputStream.
  • PipedInputStream represents the data output end in the pipeline, that is, the end where the thread reads data from the pipeline; PipedOutputStream represents the input end of the data in the pipeline, that is, the end where the thread writes data to the pipeline, these two classes can be used together to create a pipe Stream object for data input and output.
  • Once an MPS queue is created, you can use the multi-threaded communication mechanism to read and write files on the disk through the MPs queue, so that the multi-threaded program design can play a greater role in practical applications.

Take a look at the following articles:
Http://www.zhujiangroad.com/program/JAVA/1942.html


7. Why is the stop, suspend, and resume Methods eliminated, and how similar behaviors are implemented securely?

  • The suspend () method is to suspend a thread, and the resume () method is to restore a suspended thread and continue execution.
  • Suspend () and resume () Methods: these two methods are used together. suspend () causes the thread to enter the blocking state and will not be automatically restored. The corresponding resume () must be called, in order to re-enter the executable state of the thread. Typically, suspend () and resume () are used to wait for the results produced by another thread: after the test finds that the results have not yet been produced, the thread is blocked, after another thread generates the result, call resume () to restore it. If the thread that calls the suspend method tries to obtain the same lock, the program will be deadlocked.
  • The most cautious way is to have the target thread poll a variable that indicates the desired thread status (active or suspended. When the State needs to be suspended, the thread will use Object. wait to wait. When the thread recovers, Object. Y will be used to notify the target thread.
  • The stop method terminates all methods that are not terminated, including the run method. When a thread stops, it immediately releases all the locks on the lock object. This will cause the object to be inconsistent. If a method transfers money from one account to another, the deposit stops after the withdrawal. Now the bank object is destroyed. Because the lock has been released. When a thread wants to terminate another thread, it cannot know when to call stop is safe and when it will cause the object to be destroyed. So this method is discarded. You should interrupt a thread rather than stop it. In windows, a program cannot respond. In this case, the process is terminated directly in the task manager. In a similar case, You can directly use stop.
  • In most cases, you should simply modify some variables to indicate that the target thread should stop running code. The target thread should regularly check the variable and return it from its run method in a reasonable way when it is indicated that it is required to stop running (this is the method always recommended by the mongooft tutorial ). To stop instant messaging, the variable must be volatile (fast-changing) (or the access to the variable must be synchronized ).

Take a 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 interrupt a running Thread. In fact, this method throws an interrupt signal when the thread is blocked, so that the thread can exit the blocking state. More specifically, if the thread is. wait, Thread. join and Thread. if sleep is blocked by one of the three methods, it will receive an interrupt exception (InterruptedException) to terminate the blocked state early.
  • Therefore, if the thread is blocked by the preceding 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 this situation in advance) and then escape from the blocking state. In either case, the last thread checks the shared variable and stops.

9. deadlock

  • Cause of deadlock

Java thread deadlock is a classic multi-thread problem, because different threads are waiting for locks that cannot be released at all, resulting in failure to complete all the work. Suppose there are two threads, representing two hungry people respectively. They must share the knives and forks and take turns to eat. They all need two locks: the shared knife and the shared cross lock. If the thread "A" gets the knife, and the thread "B" gets the cross. Thread "A" will enter the blocking state to wait for the cross to be obtained, and thread "B" will be blocked to wait for the knife owned by ".
The root cause of the deadlock is the improper use of the "synchronized" keyword to manage the thread's access to specific objects.
A general rule of thumb to avoid deadlocks is: when several threads need to access Shared resources A, B, and C, ensure that each thread accesses them in the same order, for example, both access A first and access B and C.
Take a look at the following articles:
Http://leowzy.iteye.com/blog/740859

  • View thread deadlocks

Http://www.cnblogs.com/ilahsa/archive/2013/06/03/3115410.html


10. Self-running activity technology. We recommend that you use a design scheme to hide the run method in an anonymous internal class.

  • Self-running activity technology: starts a Thread in the Thread subclass or constructor that implements the runnable interface class;
  • Design Scheme for hiding the run method: Create a thread using an anonymous internal class in the constructor of a common class, and then start the thread.

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.