1, why to use multithreading? What are the advantages of multithreading?
Increase CPU Utilization
2, what is multi-threaded?
3, the Java implementation of multithreaded programming two ways?
A, inherit the thread class
Public class MYTHREAD01 extends Thread { @Override Public void run () { Super. Run (); System. out. println ("MyThread01"); }
Public static void main (string[] args) { MYTHREAD01 myThread01 = new MyThread01 (); Mythread01.start (); System. out. println (" Run End"); } } |
Run End MyThread01 |
| Multiple calls to start (), throwing exceptions |
public class MyThread01 extends Thread { @Override public void run () { Super . Run (); System. out . println ( "MyThread01" ); } public static void main (string[] args) { MyThread01 myThread01 = new MyThread01 (); Mythread01.start (); Mythread01.start (); System. out . println ( " Run End" ); } } |
Exception in thread "main" java.lang.IllegalThreadStateException At Java.lang.Thread.start (thread.java:705) At Com.season.testthread.MyThread01.main (mythread01.java:13) MyThread01 |
B. Implement Runnable interface
public class MyRunnable01 implements Runnable { @Override public void run () { System. out . println ( "MyRunnable01 run () ..." ); } public static void main (string[] args) { Runnable Runnable = new MyRunnable01 (); Thread thread = New thread (runnable); Thread.Start (); System. out . println ( "main () ..." ); } } |
Main () ..... MYRUNNABLE01 run () ..... |
4, two ways of comparison?
The thread class itself implements the Runnable interface;
Using the thread class to create threads, the biggest limitation is that multiple inheritance is not supported
5. What are the similarities and differences between start () and direct call run ()?
Start () in the Thread.java class notifies the thread planner that this thread is ready to wait for the calling thread object's run (). Run () is executed by the calling thread and must wait for the run () code to complete before executing the code, without having an async effect.
6. Non-thread safe?
When multiple threads operate on the same instance variable in the same object, the value is changed, the value is not synchronized, and the execution process of the program is affected.
(1) Non-sharing of data |
Public classMyThread02extendsThread { private intCount= 5; PublicMYTHREAD02 (String name) { This. SetName (name); } @Override Public voidRun () { Super. Run (); while(Count> 0) { Count--; System. out. println ("by "+ Thread.CurrentThread(). GetName () +" calculation, count= "+Count); } } Public static voidMain (string[] args) { MYTHREAD02 A =NewMYTHREAD02 ("a"); MYTHREAD02 B =NewMYTHREAD02 ("B"); MYTHREAD02 C =NewMYTHREAD02 ("C"); A.start (); B.start (); C.start (); } } |
Calculated by a, count=4 Calculated by a, count=3 Calculated by a, count=2 Calculated by a, count=1 Calculated by a, count=0 Calculated by C, count=4 Calculated by C, count=3 Calculated by C, count=2 Calculated by C, count=1 Calculated by C, count=0 Calculated by B, count=4 Calculated by B, count=3 Calculated by B, count=2 Calculated by B, count=1 Calculated by B, count=0 |
(2) Sharing of data |
Public classMyThread03extendsThread { private intCount= 5; @Override Public voidRun () { Super. Run (); while(Count> 0) { Count--; System. out. println ("by "+ Thread.CurrentThread(). GetName () +" calculation, count= "+Count); } } Public static voidMain (string[] args) { MYTHREAD03 myThread03 =NewMYTHREAD03 (); Thread A =NewThread (MYTHREAD03,"a"); Thread B =NewThread (MYTHREAD03,"B"); Thread C =NewThread (MYTHREAD03,"C"); Thread d =NewThread (MYTHREAD03,"D"); Thread e =NewThread (MYTHREAD03,"E"); A.start (); B.start (); C.start (); D.start (); E.start (); } } |
Calculated by C, count=3 Calculated by C, count=2 Calculated by C, count=1 Calculated by C, count=0 Calculated by a, count=3 |
7. How to solve non-thread safety problem?
Use the Synchronized keyword: When a thread executes the code inside a synchronous method, the thread first tries to get the lock, and if it does, the thread can execute the code inside the synchronized. If not, the thread will keep trying to get the lock until it gets there, and there are multiple threads competing for the lock.
8. API
CurrentThread () returns information about which thread the code snippet is being called. |
IsAlive () determines whether the current thread is active (the thread has started and has not been terminated). |
Sleep () lets the current "executing thread" hibernate (paused) within the specified millisecond |
GetId () Gets the unique identity of the thread |
Yield () discards the current CPU resource and gives it to other tasks to occupy CPU execution time. But the time to give up is uncertain, it is possible to just give up, and immediately get the CPU time slice. |
9, how to stop the thread?
1), use the exit flag, so that the thread exits normally, that is, when the Run method completes, the thread terminates.
2), use Stop () to forcibly terminate the thread, it is not recommended to use this method, because stop and suspend and resume, are obsolete methods, using them may produce unpredictable results. If you force a thread to stop, you may make some rational work impossible to complete. Another situation is to "unlock" the locked object, resulting in data not being synchronized and data inconsistency problems.
3), using the interrupt () in the disconnection process.
Interrupt () simply hits a stop tag in the current thread and does not really stop the thread. This.interrupted () tests if the active thread has been interrupted and has been executed with the ability to clear the status flag to False. The current thread refers to running this. The thread of the interrupted (). Interrupted () has the ability to clear the state, so the second call to interrupted () returns a value of false. This.isinterrupted () tests if the thread thread object is already in the interrupt state, but does not clear the status identity. |
A, can stop the thread--exception method |
Public class MyThread04 extends Thread { @Override Public void Run () { for (int i = 0; i < 500000; i++) { if (this. ) Interrupted()) { System. out. println ("It's already a stopped state, quit now!") "); break; } System. out. println ("i =" + (i + 1)); } System. out. println (the "for" statement runs and the thread does not stop.) "); } Public Static void Main (string[] args) { Try { MyThread04 myThread04 = new MyThread04 (); Mythread04.start (); Thread. Sleep (2000); Mythread04.interrupt (); } catch (Interruptedexception e) { System. out. println ("Main catch{} ..."); E.printstacktrace (); } System. out. println ("main () end ...."); } } |
i = 207023 Main () end .... is already in the stop state, exit immediately! The for following statement runs, and the thread does not stop. |
The above example stops the thread, but continues to run if there is a statement under for. How do I fix a problem where the statement continues to run? |
Package com.jvm.thread; Public class MyThread04 extends Thread { @Override Public void Run () { Try { for (int i = 0; i < 500000; i++) { if (this. ) Interrupted()) { System. out. println ("It's already a stopped state, quit now!") "); Throw New Interruptedexception (); } System. out. println ("i =" + (i + 1)); } System. out. println (the "for" statement runs and the thread does not stop.) "); } catch (Interruptedexception e) { System. out. println ("Enter the MyThread04 class of Run () catch{} ..."); E.printstacktrace (); } } Public Static void Main (string[] args) { Try { MyThread04 myThread04 = new MyThread04 (); Mythread04.start (); Thread. Sleep (2000); Mythread04.interrupt (); } catch (Interruptedexception e) { System. out. println ("Main catch{} ..."); E.printstacktrace (); } System. out. println ("main () end ...."); } } |
i = 220112 i = 220113 Main () end .... is already in the stop state, exit immediately! Enter the MyThread04 class of Run () catch{} ... Java.lang.InterruptedException At Com.jvm.thread.MyThread04.run (mythread04.java:10) |
|
B. Use return to stop the thread Interrupt () in combination with return |
Package com.jvm.thread; Public class MYTHREAD05 extends Thread { @Override Public void Run () { while (true) { if (this. isinterrupted ()) { System. out. println ("Stop it!" "); return; } } } Public Static void Main (string[] args) throws interruptedexception { MYTHREAD05 myThread05 = new MyThread05 (); Mythread05.start (); Thread. Sleep (2000); Mythread05.interrupt (); } } |
|
10, how to suspend the thread?
Pausing a thread means that the thread can also resume running. In Java Multi-threading, you can use suspend () to pause a thread and resume () The execution of a thread.
Suspend and the disadvantage of the resume method--monopoly
The disadvantage of suspend and resume method--out of sync
11. Priority of Threads
In the operating system, threads can prioritize, and higher-priority threads get more CPU resources, which means that the CPU takes precedence over the tasks in the county's objects with the highest precedence.
Setting the thread priority helps help the group thread planner determine which thread to select next time to take precedence.
Precedence has randomness.
12. Daemon Thread
There are two kinds of threads in a Java thread, one is a user thread and the other is a daemon thread.
When a non-daemon thread is not present in the process, the daemon thread is automatically destroyed. A typical daemon thread is a garbage collection thread.
(1) Java multithreaded Programming core--java multithreading skills