When a program goes into memory run, it becomes a process, process characteristics: independence, dynamic, concurrency. A thread is also known as a lightweight process, a thread is the execution unit of a process, a thread is a separate, concurrent execution flow in a program, a thread can have its own stack, program counters, and its own local variables, but does not own system resources, and it shares all of the resources owned by the process with other threads of the parent process. Thread execution is preemptive, and threads have higher performance than processes.
1) differentiate concurrency and parallelism:
Concurrency: Only one instruction is executed at a time, and multiple process instructions are quickly rotated to execute.
Parallelism: Multiple instructions are executed simultaneously on multiple processors at the same time.
2) Benefits of using multithreaded programming:
The process can not share memory, but between threads, using multithreading to achieve multi-tasking is more efficient than multi-process, Java built-in multi-threaded feature support.
1. Create a thread
1) Create and start multithreading by inheriting the thread class
public class MyThread extends thread {private int i;//Override the Run method, the method body of the Run method is the thread execution body public void run () {for (; i <; i+ +) {///when the thread class inherits the threads class, use this directly to get the current thread//thread object's GetName () to return the current thread's name System.out.println (GetName () + "" + i);}} public static void Main (string[] args) {for (int i = 0; i <; i++) {//calls the thread's CurrentThread method to get the current thread System.out.println (Thread.CurrentThread (). GetName () + "" + i); if (i = = 20) { New MyThread (). Start (); Create and start the first thread new MyThread (). Start (); Create and start the second thread}}}}
2) Implement Runnable interface Create thread class
public class MyThread2 implements Runnable {private int i;//The Run method is also the thread execution body public void run () {for (; i <; i++) { When the thread class implements the Runnable interface, you can only use the Thread.CurrentThread () method System.out.println (Thread.CurrentThread () If you want to get the current thread. GetName () + " "+ i);}} public static void Main (string[] args) {for (int i = 0; i <; i++) {System.out.println (Thread.CurrentThread (). GetName () + " " + i), if (i = =) {MyThread2nd = new MyThread2 (); The new Thread (ST, "new Thread 1") is created by using the newly threaded (target, name) method. Start (); New Thread (St, "2"). Start ();}}}
3) Implement the callable interface to implement the threading class
public class MyThread3 {public static void main (string[] args) {//Create callable object MyThread3 RT = new MyThread3 ();//Use Lambda first Expressions create Callable<integer> objects//Use Futuretask to wrap callable objects futuretask<integer> task = new futuretask< Integer> ((callable<integer>) (), {int i = 0;for (; i < i++) {System.out.println (Thread.currentthre The value of the loop variable I for AD (). GetName () + ":" + i);} The call () method can have a return value of returned I;}); for (int i = 0; i < i++) {System.out.println (Thread.CurrentThread (). GetName () + "The value of the loop variable i:" + i); if (i = = 20) {/ /In essence or callable object to create, and start threading new Thread (task, "Thread with return value"). Start ();}} try {//Get thread return value System.out.println ("Child thread return Value:" + task.get ());} catch (Exception ex) {ex.printstacktrace ();}}}
Note: If you call the Run method directly when you start the thread, the Run method executes immediately, and other threads cannot execute concurrently until the Run method returns, becoming a single-threaded procedure.
2. Three ways to create threads compare
1) inherit the thread class to create multithreading
Advantages: Easy to write, easy to access the current thread, use this directly.
Disadvantage: You cannot inherit other parent classes
2) Implement Runnable interface or callable interface to create multithreading
Pros: Share a target object that is suitable for multiple threads to handle a resource situation.
Cons: Programming is relatively complex, and accessing the current thread must use the Thread.CurrentThread () method.
It is generally recommended to implement Runnable interface or callable interface to create multithreading
3. Thread Life cycle
The thread state transition diagram is as follows:
Note:1) If the program calls the child thread's start () method after the child thread executes immediately, the program can use Thread.Sleep (1) to let the currently running thread (the main thread) sleep for 1 milliseconds. 2) The thread's Stop method is dropped directly to end the thread, which is prone to deadlock and is generally not recommended for use. 3) The test thread is dead. You can use the IsAlive () method, which returns True when the thread is ready, running, or blocking three states, and returns False when the thread is in a new, dead two state. 4) Do not call the start () method on the thread that is dying, or the illegalthreadstateexception exception will be thrown.
4. Control Threads
1) Join ()a method that allows one thread to wait for another thread to finish
2) Background threadfeature: If the foreground thread is dead, the background thread is dead. the Setdaemon (True) method of the thread object is called to set the specified thread as a background thread. The Isdaemon () method is used to determine whether the specified thread is a background thread, and the mainline Cheng considers the foreground thread.
3) Sleep static method of the thread class sleep (long Millis);
Used to pause the execution of a program, pausing Millis milliseconds, and entering a blocking state.
4) Thread concession: Yield pauses threads, does not block threads, but transfers threads to a ready state
5) Change thread priority set to highest priority:. SetPriority (Thread.max_priority)
set to lowest priority:. SetPriority (Thread.min_priority)
Change the priority of the main thread: Thread.CurrentThread (). setpriority (6);
5. Thread Synchronization
Troubleshoot thread safety issues
1) Synchronizing code blocksSyntax:
Synchronized (obj) {//obj: Synchronization monitor, the thread must first obtain a lock/synchronize code block to the synchronization monitor before it starts executing the synchronization code block}
It is generally recommended to use a shared resource that may be concurrently accessed as a synchronization monitor
public class Drawthread extends thread {... public void run () {///Use account as the synchronization monitor, before any thread enters the following synchronization code block,//must first obtain a lock on accounts- -Other threads cannot get a lock and cannot modify it//This practice conforms to: "lock → modify → release lock" logic synchronized (obj) {...} Synchronization code block ends, the thread releases the Sync Lock} ...}
2) Synchronization method
The synchronous method is to use the Synchronized keyword to decorate a method (the Synchronized keyword can modify a method, a code block, but not a constructor, member variable ).
public class Account {...//provides a thread-safe draw () method to complete operation public synchronized void draw (double drawamount) {...} ...}
Expand:
In order to reduce the negative effect of thread safety, the thread safety of variable class is to reduce the running efficiency of the program, the program can adopt the following strategy:
A) Do not synchronize all methods of the thread-safe class, only those that will change the competing resources.
b) If the variable class has two operating environments (single-threaded and multithreaded), you should provide a thread-insecure version of the Mutable class (using a thread-unsafe version in a single-threaded environment to ensure performance) and a thread-safe version.
3) Release the Sync monitor lock
A) The thread releases the lock on the synchronization monitor in the following situations:
Synchronization method, synchronization code block execution end;
Synchronization method, synchronization code block encountered a break, return terminated execution;
An unhandled error or exception has occurred;
The wait () method for the synchronization monitor is executed, and the current thread pauses and releases the synchronization monitor .
b) The thread does not release the lock on the synchronization monitor in the following situations:
Call the Thread.Sleep (), Thread.yield () method to pause the execution of the current thread;
Other threads call the thread's suspend () method to suspend the thread.
4) Sync Lock (Lock)
Lock (JAVA5 new feature) provides a wider range of locking operations than the Synchronized method and synchronized code blocks, and lock allows for a more flexible structure that can have very different properties, and supports multiple related condition objects.
5) Deadlock
A deadlock occurs when two threads wait for each other to release the Sync Monitor
Java Multi-threaded adventure