Multithreading and java Multithreading
I. Overview 1. What is a process?
A process is a relatively independent execution unit.
2. What is a thread?
Part of the process, the actual task executor in the process, must be attached to the process. The thread dependency on the process is mainly reflected in:
- The thread cannot be enabled without the process. It must be enabled only when the process is enabled.
- Sometimes the thread must obtain data from the process.
3. What is the difference between a thread and a process?
A thread and a process are two opposite concepts. The execution unit of an object relative to it is called a process. It is also called a thread in terms of its superior executor.
4. design purpose, purpose, and significance of Multithreading
The CPU can only execute one thread at any time point. The essence of Multithreading is that multiple tasks are executed at high speed. If there is no data exchange between multiple threads, it can be executed independently. Using Multiple Threads does not reduce the total execution time.
The main purpose of the multi-threaded design is not to increase the execution speed, but to execute each thread relatively evenly, so that a thread does not hold the CPU time slice for a long time, and other threads are waiting for a long time. Since the CPU time slice quickly switches between multiple threads and beyond the scope that human senses can perceive, it feels that multiple tasks are executed.
For example, when multiple people access the same website, it takes five minutes for each person. If multithreading is not used, only one person is allowed to access the website. Most people will wait five minutes, poor user experience. This is a multi-thread approach. After a person enters the system, the CPU is switched to other users, allowing other users to access the system one after another, improving the user experience, even though the overall execution time has not been reduced.
5. CPU scheduling mode
- Time-sharing scheduling mode: The system evenly allocates CPU time slices for each thread.
- Preemptible scheduling mode: Each thread grabs the CPU time slice, And the CPU time slice is allocated unevenly between threads.
Two-thread creation 1. Java se api provides two ways to create a thread:
- Implement the Runnable interface and pass the object of the implementation class as a parameter to the constructor of the Thread.
- Directly inherit the Thread class.
2. No matter which method is used, the tasks to be executed must be placed in the run method. 3. Differences between the two creation methods:
(1) Java uses single inheritance, that is, a class can only inherit one parent class, while a class can implement multiple interfaces and create threads by inheriting Thread, this class loses the only inheritance opportunity.
(2) Different resource sharing methods
- First, we need to clarify that resource sharing can also be realized by inheriting the Thread creation Thread, because multiple threads created by using the new keyword are different objects, therefore, shared resources can only come from external sources and are usually injected through the constructor.
- By implementing the Runnable interface, you can use the same implementation class object to create multiple threads to achieve resource sharing. The shared resources come from within the thread.
4. Using the Runnable interface to create a thread not only retains the unique inheritance opportunity, but also facilitates Resource Sharing. Therefore, this method is generally used to create a thread.
5. Share resources by inheriting the Thread:
External classes that provide shared resources
package com.test.thread.extendsThread;public class MyClass { public int count;}
Thread subclass
Package com. test. thread. extendsThread; public class MyThread extends Thread {private MyClass obj; public MyThread () {super ();} public MyThread (MyClass obj) {super (); this. obj = obj;} @ Override public void run () {System. out. println ("obj =" + obj); while (true) {synchronized (obj) {if (obj. count> 0) {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "---- current number =" + obj. count --) ;}else return ;}}}}
Test class
Package com. test. thread. extendsThread; import org. junit. test; import com. test. thread. synchronizedTest. demo02.MyTestRunnable; import net. sourceforge. groboutils. junit. v1.MultiThreadedTestRunner; import net. sourceforge. groboutils. junit. v1.TestRunnable; public class ThreadExtendsTest {/*** the JUnit unit test does not support multi-thread testing. You can use GroboUtils for multi-thread testing (import the rack package) ** @ throws Throwable */@ Test public void test01 () throws Throwable {MyClass obj = new MyClass (); obj. count = 10; MyThread myth01 = new MyThread (obj); MyThread myth02 = new MyThread (obj); MyThread myth03 = new MyThread (obj); MyTestRunnable t01 = new MyTestRunnable (myth01 ); required t02 = new MyTestRunnable (myth02); MyTestRunnable t03 = new MyTestRunnable (myth03); TestRunnable [] tr = new TestRunnable [3]; tr [0] = t01; tr [1] = t02; tr [2] = t03; MultiThreadedTestRunner mttr = new MultiThreadedTestRunner (tr); mttr. runTestRunnables ();} // test public static void main (String [] args) {MyClass obj = new MyClass (); obj. count = 10; MyThread t01 = new MyThread (obj); MyThread t02 = new MyThread (obj); MyThread t03 = new MyThread (obj); t01.setName ("t01 "); t02.setName ("t02"); t03.setName ("t03"); t01.start (); t02.start (); t03.start ();}}
Three-thread life cycle 1. What is the life cycle of a thread?
The whole process of a thread consisting of different stages from birth to death is called the life cycle of the thread.
2. Significance of thread Lifecycle
Knowing the life cycle of a thread can better understand the running status of the thread, such as the ready state of the thread, means that the thread is executed immediately after the start method is called.
3. Several stages of the lifecycle:
- Birth status: the status before the thread is created and enabled.
- Ready state: the state in which the start method is called to enable the thread and the thread is not running.
- Running status: the status when the thread obtains the CPU time slice for execution.
- Sleep Status: After the thread calls the sleep method, it enters the sleep status with a specified duration and enters the ready state after the time ends.
- Waiting status: After the listener object calls the wait method inside the thread, the thread loses the object lock and enters the waiting status.
- Blocking status: the thread enters the blocking status after sending an input or output request.
- Death state: the run method is completed, and the thread is killed.
Add four threads
One thread A calls the join method in another thread B. The thread B is suspended. The thread A starts to run. The thread A is finished and the thread B starts to run.
Five-thread priority
The thread priority specifies the probability that a thread obtains a CPU time slice. It is only a probability that a thread with a higher priority cannot obtain a CPU time slice first.
The thread priority is divided into 10 levels, from 1 to 10. The greater the value, the higher the priority. It is set through the setProprity (int) method.
Six-thread courtesy
Thread. yield, Thread courtesy only notifies the current Thread that resources can be presented to other threads, and does not guarantee that the current Thread will definitely give up resources.
7. Synchronization Mechanism 1. What is thread synchronization mechanism?
This ensures that only one thread can access the same resource at a time. That is, only one thread can access other threads after access is completed.
2. The purpose of the synchronization mechanism
The thread security problem is solved because the target resource only has one thread to access at the same time.
3. What is thread security? (1) Conditions for thread security issues
- Multi-thread concurrent access.
- Shared data that can be modified exists.
(2) The first thread obtains the shared data. Before the operation ends, the second thread modifies the data. As a result, the first thread does not use the data obtained during computation. 4. Principles of synchronization mechanism to solve thread security problems
Synchronized (shared object) {code for modifying shared data}
The above operation adds an object lock to the Code for modifying shared data. Each object has only one lock, and the thread can only access the locked resources after obtaining the object lock. A thread obtains the object lock, executes the lock code, finishes the execution, and returns the object lock. Other threads start to compete for the object lock and access resources.
5. Category lock
When the synchronized keyword is added to a static method, a class lock is formed. You must obtain the class lock when executing this method.
Two types of locks are available: one thread can hold the locks, and the other thread can hold the Object locks.
6. synchronized keyword
The synchronized keyword is added to the member method. This method becomes a synchronization member method. Because an object has only one object lock, one thread accesses one synchronization member method, and other threads cannot access other synchronization member methods.
The synchronization method cannot be inherited. The synchronization method does not have the synchronization mechanism in the subclass.
7. Set judgment Conditions
In the synchronization mechanism, if the execution of the synchronization code meets certain conditions, the judgment condition is placed in the lock to ensure that the thread that obtains the lock meets the execution condition when executing the synchronization code. If it is placed outside the lock, the execution condition may not be met after the current thread obtains the lock.
There is no thread security problem:
Public void run () {System. out. println ("obj =" + obj); while (true) {synchronized (obj) {if (obj. count> 0) {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "---- current number =" + obj. count --) ;}else return ;}}}
If you place the judgment condition obj. count> 0 in the while statement, it may occur that when a thread enters the while statement, count is 1. If the condition is met, enter and wait for the object lock to be obtained. The thread currently holding the object lock is executed, and the count is changed to 0. Wait for the thread to obtain the object lock and execute the synchronization block when the count is 0 to judge that the condition is invalid.
8. deadlock 1. What is a deadlock?
Thread A requires multiple locks. Thread B holds the lock that A lacks and the lock that A holds. Because the thread does not release the lock that it holds before obtaining all the locks, this causes the deadlock between thread A and thread B, and the whole process is in A stopped state.
2. How to avoid deadlocks?
Reduce the number of locks in the synchronization mechanism and avoid the occurrence of the same lock in multiple places.
Nine daemon threads 1. User threads?
Generally, the created thread is a user thread, that is, the thread is not explicitly set as a daemon thread and is not created in the daemon thread.
2. The main thread belongs to the user thread. 3. What is a daemon thread?
A thread that runs in the background and provides services for user threads.
4. daemon thread Creation
The user thread calls the setDaemon (true) method, or creates a thread in the daemon thread.
5. Role of daemon
The daemon thread is used to provide services for user threads, such as the garbage collector.
6. The JVM is terminated after all user threads are executed, whether or not the daemon thread is executed. 7. The daemon thread runs in the background and ends automatically after all user threads are finished. 10. Comparison between wait and sleep methods 1. Scope
- The wait method is Object-level, that is, any Object in java has this method, like toString.
- The sleep method only exists in the Thread and its subclass.
2. Role
- Sleep the current thread and releases the CPU time slice.
- Wait is used for inter-thread communication. The object manages all threads with this object as the lock. The lock object is called in the synchronization code to release the lock held by the current thread.
3. Usage
- The sleep method is a static method called directly through Thread. sleep.
- Used in the synchronization code, called by the Lock Object.
4. Related Methods
- Obj. Y (): Randomly wake up a thread on the object listener. The thread enters the ready state. Once the object lock and CPU time slice are obtained, the thread is executed from the waiting position, do not re-enter the run method or synchronize the code.
- Obj. policyall (): wake up all the waiting threads on the object listener and make them all ready.
Eleven ThreadLocal
1. The local variable of the thread provides a copy of the variable for each thread, so that each thread operates the variable relatively independently to avoid thread security issues.
2. You must first make it clear that a copy of the variable obtained by ThreadLocal. get () must be passed in manually:
ThreadLocal.set(Object obj)
When obtaining the object for the first time, check whether a copy of the variable is saved in the local variable of the thread. If not, manually import the object.
3. ThreadLocal is designed to ensure that it is created at a time within a thread and obtained multiple times.
4. Basic Principles:
Bind the first input variable to the thread. The thread remains unchanged and the variable remains unchanged.
12 GroboUtils multi-thread Test 1. JUnit test does not support multithreading. GroboUtils provides support for multi-thread test and needs to import the shelf package for use. 2. Several important classes:
- TestRunnable: implements the Runnable interface. The run method runs the runTest method, and the runTest method is an abstract method.
- MultiThreadedTestRunner: Manages and enables multiple threads.
3. Test Procedure
(1) inherit TestRunnable, implement the abstract method runTest, and put the code to be run into this method. Generally, a constructor with parameters is defined for the subclass. The method parameter is the thread to be tested. In the runTest method, the run method of the test thread is called to inject the code to be executed into the runTest method.
(2) create a test thread array and pass the TestRunnable implementation class to be tested:
TestRunnable[] tr=new TestRunnable[len];
(3) create thread management and running Objects Based on the test thread array and enable multithreading:
MultiThreadedTestRunner mttr=new MultiThreadedTestRunner(tr);mttr.runTestRunnables();