Multithreading
1 , Process
Process: When a program goes into memory run, it becomes a process. Process is independent, dynamic, and concurrency.
A, independence: The process is a separate entity in the system, it can have its own independent resources, each process has its own private address space. A user process cannot directly access the address space of another process without the process itself allowing it.
B, Dynamic: The difference between a process and a program is that the program is a static set of instructions, and the process is a running set of instructions. Process has the concept of time, has its own life cycle and a variety of different states, and the program does not have this concept.
C, Concurrency: Multiple processes can execute concurrently on a single processor without affecting each other.
2 , Thread
Threads: Threads are lightweight processes, are execution units of processes, and are part of a process. Threads have independence, concurrency, sharing, preemption.
A, Independence: Each thread is also run independently.
B, Concurrency: Multiple threads can execute concurrently.
C, sharing: Threads can have their own stacks, counters, local variables, etc., but do not have system resources, multiple threads in the same process share the parent process's system resources.
D, preemption: The execution of a thread is preemptive, and the current thread can be suspended at any time so that another thread can run, and one thread may end another.
Description: There is at least one process after a program has run and at least one thread in a process.
3 , inheritance Thread class creation Thread
To create a threading method:
public class ClassName extends Thread
{
public void Run ()
{
Overriding the method body of the run () method of the parent class
}
public static void Main (string[] args)
{
New classname (). Start ();
}
}
Steps:
A, define a subclass of the thread class, override the Run () method, the method body of the run () method represents the task that the thread needs to complete, so the run () method is called the thread execution body.
B. Create an instance of the thread subclass, which is the object that created the threads.
C. Call the Start () method of the thread object to start the thread.
Description
A, Java uses the thread class to represent threads, and all thread objects must be instances of the thread class or its subclasses.
B, the Main method represents the main thread.
C, Thread.CurrentThread (): This is a class method that returns the currently executing thread object.
D, GetName (): This is an instance method that returns the name of the thread that called the method.
E, SetName (String name): This method can set the name of the thread, the thread name defaults to Thread-0, Thread-1 ...
F, when creating a thread by inheriting the thread class, multiple threads cannot share instance variables of the thread class.
4 , achieve Runnable interface Create thread class
public class Classname implements Runnable
{
public void Run ()
{
Business code
}
public static void Main (string[] args)
{
Classname cl = new Classname;
The new thread (CL, "fresh Thread"). Start ();
}
}
Steps:
A, define the implementation class for the Runnable interface, and override the run () method of the interface, and run () is also the thread execution body of the thread.
B, create an instance of the Runnable implementation class, and use this instance as the target of the thread to create the thread object, which is the true thread object.
C. Call the Start () method of the thread object to start the thread.
Description
A, in the Run () method of the class that implements the interface, to get the current thread object must be called with the class name, Thread.CurrentThread (), and the Run () method that inherits the parent class can use this call.
B, the thread that implements the Runnable interface can share the instance variable of the thread class (which is actually the target class), because the inheriting class creates two instances of the inheriting class when the two threads are created, and the instance variables of the different instances point to different memory regions, while implementing the interface class creates the thread. Provides only its own reference to assist the thread to create the object, this reference can be reused, so not to create multiple interface class objects, so the interface class object is naturally pointed to the same storage area.
5 , using callable and the Future Creating Threads
public class Classname
{
public static void Main (string[] args)
{
futuretask<integer> task = new future<integer>
(
(callable<integer>) ()
{
int j = 0;
Business code
Return J;
}
)
New Thread (Task, "Thread with return value"). Start ();
Try
{
System.out.println ("The return value of the child thread:" +task.get ());
}
catch (Exception ex)
{
Ex.printstacktrace ();
}
}
}
Steps:
A, create an implementation class for the callable interface, and implement the Call () method, which will act as the thread execution body, and the call () method has a return value, and then creates an instance of the callable implementation class. Because the callable interface is a functional interface in JAVA8, you can create callable objects directly using lambda.
B. Use the Futuretask class to wrap the callable object, which encapsulates the return value of the call () method of the Callable object.
C. Use the Futuretask object as the target of the thread object to create and start a new thread.
D. Call the Get () method of the Futuretask object to get the return value after the child thread execution ends.
6, the life cycle of the thread
Description: A total of 5 state, new, Ready (Runnable), run (Running), blocking (Blocked), and Death (Dead) are in the lifetime of the thread.
7. New status
A. Create A thread with the New keyword and you are in the new state.
B, the JVM virtual machine allocates memory for it, initializes the member variable value.
C, the thread object does not have a dynamic attribute at this time and does not execute.
8. Ready state
A, when the thread object calls the start () method, the thread is in the ready state.
B, the JVM creates method call stacks and program counters for it.
C, this time the thread can run, but not run, when run, depending on the JVM thread scheduler scheduling.
9. Operation Status
A, the thread is in a ready state, gets the CPU, starts executing the run () method, and is in the running state.
B, a CPU can only run one thread at any one time.
10. Blocking status
A, blocking state means that the running state is interrupted, system resources are retracted, and other threads are started.
B, the thread calls the sleep () method to actively discard the occupied processor resources, into the blocking state.
C, the thread calls the blocking Io method, and the thread is blocked until the method returns.
D, the thread attempted to obtain a synchronization monitor, but the monitor was held by another thread and went into a blocking state.
E, the thread is waiting for a notification (notify).
F, the program call thread's suspend () method suspends the thread and enters a blocking state, which is prone to deadlock and should be avoided as much as possible.
H, when the thread is blocked, the other thread gets the execution opportunity, and the thread enters the ready state at the appropriate time and starts over again.
I, call the Sleep () method time is up, the thread contact is blocked into the ready state.
J, the blocking Io method called by the thread has been put back, and the thread is unblocked into the ready state.
K, the thread successfully obtained the attempted synchronization monitor, the thread unblocked into the ready state.
M, when a thread waits for a notification, the other thread sends a notification that the thread is unblocked into a ready state.
N, the thread in the suspended state is called the Resume () recovery method, and the thread is unblocked into the ready state.
11. Death Status
A, run () or call () method execution ends, thread dies.
B, the thread throws an uncaught exception or error, and the thread dies.
C, directly call the thread of the Stop () method to end the thread, thread death, but easy to deadlock, is not recommended to use.
E, the end of the main thread will not affect other threads.
F, tests if a thread is dead, calls the thread object's IsAlive () method, returns True when it is in the ready, running, and blocked state, and returns False when it is in the new, dead state.
G, do not call the start () method on the dead thread to try to start it, death is death.
H, it is also an error to call the start () method on a new state thread two times.
12. Control Threads
(1) Join thread
A, the thread class provides a join () method, thread 1 calls the Join () method of thread 2, thread 1 is blocked, thread 2 executes, thread 2 executes, and thread 1 resumes execution.
B, join (): Waits for the join thread to execute.
C, join (Long Millis): The thread that waits for the join to be executed is the longest of millis milliseconds, exceeding the range.
D, join (Long Millis,int Nanos): The thread that waits for the join is the longest millis milliseconds +nanos microseconds.
(2) Background thread
A, a thread running in the background that serves other threads, called a background thread (Daemon thread), daemon thread, or sprite thread.
B, the foreground thread is dead, the background thread will die automatically.
C. Call the Setdaemon (True) method of the Thread object to specify that the thread setting is called a background thread.
The thread class provides a Isdaemon () method that determines whether the specified thread is a background thread.
(3) Thread Sleeping: Sleep ()
If you want the currently executing thread to pause for a while and go into a blocking state, you can do so by calling the static method of the thread class sleep method, which has two overloaded forms.
A, static void sleep (Long Millis): lets the currently executing thread pause Millis milliseconds and into a blocking state, affected by the system timer and thread scheduler precision.
B, static void sleep (Long millis,int Nanos): Lets the currently executing thread pause Millis milliseconds +nanos microseconds, and into the blocking state, affected by the system timer and thread scheduler precision.
C, during sleep time, even if no other thread is running, the thread will not run, so the Sleep () method is often used to pause thread execution.
(4) Thread concession: yield
The A, yield () method is also the class method provided by the thread class, but it can also suspend the current thread, but it will not block the current thread, just let it go into a ready state and wait for the thread scheduler to call back.
B. The thread that called the yield () method has the opportunity to execute only if the priority is the same or higher than the current thread.
(5) The difference between the yield () method and The Sleep () method:
Sleep (): ignores other thread priorities.
A, priority
Yield (): Only execution with the same or higher priority.
Sleep (): After the call into the blocking state, after blocking time into the ready state.
B, blocking
Yield (): Force into the ready state.
Sleep (): Throws an interruptedexception exception, either snaps or explicitly declares the throw.
C, exception
Yield (): does not throw an exception.
Sleep (): good.
D, transplant sex
Yield (): poor, it is generally not recommended to use the yield () method to control concurrent thread execution.
(6) Changing thread priority
A, thread execution has a certain priority, high-priority threads get more execution opportunities.
B, the default priority for each thread is the same as the parent thread that created it, for example, the main thread is a normal priority, and the child thread that it creates is also the normal level of precedence.
C, the thread class provides the setpriority (int newpriority), getpriority () method to set and return the priority of the specified thread, newpriority can be an integer in 1-10, or the following constants:
A, max_priority: the value is 10
B, norm_priority: The value is 5
C, min_priority: The value is 1
D. Use constants as much as possible to set priorities to ensure portability.
13. Thread Synchronization
(1) When two processes modify the same file concurrently, it is possible to cause an exception.
(2) multithreading introduces synchronization monitor to solve this problem, the format is as follows:
Synchronized (obj)
{
...
Synchronizing code blocks
}
Description: obj is the synchronous monitor, which means that the synchronization monitor must be locked before the thread executes the synchronization code.
A, at any time, only one thread can get a lock on the synchronization monitor, and when the synchronization code block finishes executing, the thread releases the lock on the synchronization monitor.
b, any object can act as a synchronization monitor, but it is recommended to use a shared resource that may be accessed concurrently as a synchronization monitor.
C, using the synchronization monitor, you can ensure that concurrent threads only one thread at a time can enter the code area (also called the critical section) that modifies the shared resource, thus guaranteeing thread security.
(3) Synchronization method: The method of using synchronized modification. For an instance method (non-static) that is synchronized decorated, it is not necessary to explicitly specify the synchronization monitor, which is the monitor for the synchronous method, or the object that invokes the method.
(4) Do not synchronize the methods of thread-safe classes, and synchronization is at the expense of efficiency.
(5) Release the lock on the sync monitor
Any thread entering the synchronization code block must first obtain a lock on the synchronization monitor, but the lock release of the synchronization monitor is not explicit, and only one situation will release the lock:
A, the current thread's synchronization method, the synchronization code block execution ends, the current thread releases the synchronization monitor.
b, the current thread encounters a break in a synchronous code block, a synchronous method, a return terminates the code block, and the method continues execution, and the current thread releases the synchronization monitor.
c, the current thread in the synchronization code block, the synchronization method has an unhandled error or exception, resulting in a code block, the method at the end of the exception, release the synchronization Monitor.
D, when the current thread executes a synchronous code block or synchronous method, the program executes the Wait () method of the synchronization monitor object and releases the synchronization monitor.
The synchronization monitor is not released when:
A, when a thread executes a synchronous block of code, a synchronous method, the program calls the Thread.Sleep (), Thread.yield () method to pause the current thread and does not release the synchronization monitor.
b, when a thread executes a synchronous code block, other threads call the thread's suspend () method to suspend the thread, and the thread does not release the synchronization monitor.
14. Sync Lock (Lock)
In the process of implementing thread safety, it is common to use Reentrantlock (Reentrant lock), which can be used to explicitly locking and release locks in the following format:
Class X
{
Private final Reentrantlock lock = new Reentrantlock ();
public void M ()
{
Lock.lock ();
Try
{
Code that needs to be thread-safe
}
Finally
{
Lock.unlock ();
}
}
}
15. Deadlock
Deadlock: When two threads wait for each other to release the Sync Monitor, they enter a deadlock.
Consequence: The entire program will not have an exception, and will not give any hint, all the threads are in a blocking state and cannot continue execution.
16. Thread Communication
(1) Traditional thread communication:
A, wait (): Causes the current thread to wait until another thread calls the synchronization Monitor's notify () method or the Notifyall () method to wake.
Wait (): Wait until the notification wakes up.
Wait (long Millis): Automatically wakes up after waiting for millis milliseconds.
Wait (long Millis,int Nanos): Waits Millis milliseconds +nanos microseconds, automatically wakes up.
When the wait method is called, the thread releases the lock on the synchronization monitor.
b, notify (): Wakes up a single thread waiting on this synchronization monitor. If all threads are waiting on this synchronization monitor, then selective wake-up of a thread is optional. The condition on which a thread is awakened is that the current thread waits with the Wait () method to discard the lock on the synchronization monitor.
C, Notifyall (): Wakes up all the threads waiting on this synchronization monitor. Only when the front-thread abandons the lock on the synchronization monitor will the awakened threads have an opportunity to be executed.
The synchronized modifies the default instance of the synchronous method when this is called directly in the synchronous method.
Synchronized modified synchronization code block, the synchronization monitor is the object in parentheses, you must use the object to invoke the method.
(2) using condition to control thread communication
When using the lock object to ensure synchronization, there is no implicit synchronization monitor in the system, so you cannot use wait, notify and other methods for thread communication, a condition object is required instead of the function of the synchronization monitor, condition object is bound to the lock object , you can create a condition object by calling the Newcondition () method in the lock object.
A, await (): Similar to wait (), causing the current thread to wait, there are many variants, such as Long Awaitnanos (long nanostimeout), can complete a richer wait operation.
b, Signal (): Wakes a single thread waiting on this lock object, all threads wait on the lock object, chooses to wake one of the threads, and chooses to be arbitrary. The wake-up thread can only be executed if the front-thread discards the lock object (using the await () method).
C, Signalall (): Wakes all the threads waiting on this lock object. The wake-up thread can only be executed if the front-thread discards the lock object (using the await () method).
(3) using a blocking queue (blockingqueue) to control thread communication
A, Blockingqueue is a thread-synchronous interface, which is the sub-interface of the queue.
B, blockingqueue feature: When a producer thread tries to put an element into the Blockingqueue, the thread is blocked if the queue is full. When a consumer thread attempts to remove an element from Blockingqueue, the thread is blocked if the queue is empty.
C, the program's two threads alternately into the blockingqueue element, take out the element, you can control the thread communication very well.
17. Thread groups and unhandled exceptions
A, Java uses Threadgroup to represent thread groups, which can classify a batch of threads.
B, the user-created thread belongs to the specified group, no display specified, and belongs to the default group.
C, by default, the child thread is within the same group as the parent thread that created it.
D. Once a thread joins the specified group, the thread remains in that group until it dies.
The E, Threadgroup class provides two constructors to create an instance:
A, Threadgroup (String name): Creates a new thread group with the specified thread group name.
B, Threadgroup (Threadgroup parent,string name): Creates a thread group with the specified parent thread and the specified name.
C, the GetName () method can be used to get the name of the thread group.
F, the following methods can be used to manipulate the entire thread group:
A, int activitycount (): Returns the number of active threads in the thread group.
B, Interrupt (): Interrupts the thread in this thread group.
C, Isdaemon (): Determines whether the thread group is a background thread group.
D, Setdaemon (Boolean daemon): Sets the thread group as a background thread group.
E, setmaxpriority (int pri): Sets the highest priority of the thread group.
G, void Uncaughtexception (Thread t,throwable e)
The method defined in Threadgroup can handle unhandled exceptions thrown by any thread within the thread, and T is the thread that has the exception, and E represents the exception that the thread throws.
"Java" Multithreading _ Learning Notes