Summary of Knowledge points: (see example)
Multithreading:
Threads are created separately in the programControl Unit, is a program that executes concurrently. The procedure executed in the external order is calledMain Thread。
A thread is a multi-tasking operating system that calls the CPU to switch back and forth.
Note: Thread-open to use the Start method, the virtual machine calls the underlying application for a separate thread to the operating system. If you only execute the Run method,
Then it does not open a thread, just a normal class method, which is executed sequentially in the main thread. You turn on Start is false
The machine automatically calls the Run method after a new thread is opened.
Windows executes a virtual machine, a virtual machine executes a multithreaded program, a multi-threaded procedure calls the underlying Windows, and eventually windows calls itself.
five states of thread:
Create, Perish: The Stop method or the Run method finishes executing
Temporary state: Blocked. There is an executive qualification but no enforcement right.
Sleep,wait is a frozen state, giving up execution eligibility.
After notify, back to the temporary state, not necessarily run, because not necessarily rob the executive right.
Because our thread inherits the thread parent class, we use super to call the parent class constructor method to give the name
Sell Tickets:Multithreading shares the same resources, defined as static. Ticket--, 1:2, number 3rd is first printed out as a dual-core CPU, because the call
Printing at the command line is also a program. If not defined as static, ticket still inherits the thread replication Run method, then there can be only one
window to sell tickets. Soto create an object with multi-threaded execution in another way.
Let the thread call the Run method of the class that implements Runnable.
The difference between implementation and inheritance: (Face-try-point) Java single-root inheritance structure, inherited classes can no longer inherit thread
Security issue: When multithreading executes the same resource as a piece of code. Here's a ticket to the last ticket, maybe a thread hangs
Before tickets--, another thread came in, output after tickets--, then the ticket has been 0, waiting for the thread to execute, appears 0
, -1,-2 ticket, etc.
Cause: Multiple statement operations share data, one thread executes only a portion of multiple statements, and another process participates in a common
To enjoy data errors.
WORKAROUND: Synchronize the statements that share data with multiple operations (synchronous code block, the lock is a unique object on the run), and determine
Like state, enter, lock state, execute, until the thread finishes executing, unlocks, other lines friend come in. Lock, lock flag, monitor.
Synchronization Prerequisites: 1. Two or more than two threads 2. Must be multiple threads using the same lock (executing the same synchronization code)
The Run method is single-threaded if it is kept in sync. Code that does not need to be synchronized does not need to be in sync at all.
the lock for the synchronization function is this
Proof: Write a synchronous function and a synchronous code block with this as the lock, the content is the operation of the same resource, two threads each run
Note that if the synchronization code block is not using this lock, because it is not the same lock, then two threads are not synchronized, each running
Each, the operation is the same resource of multiple statements, then there will be a thread security issue.
the lock of a static synchronization function is a class byte-code file Object
Verification: Changing the lock of the above example synchronization code block to this bytecode file object will ensure thread safety, not a wired thread security issue
Deadlock: The synchronization code block is nested, with the same lock, two threads each need each other's lock.
A few examples:
1. Sell Tickets: thread safety resolved (the same resource for multithreaded operations of multiple statements)
Package Cn.xbai.thread;class Ticket implements Runnable{private int. Tickets=100;public void Run () {while (true) { Synchronized (this) {if (tickets<=0)//must try their own, see the effect of knowledge points to understand the right, the solution can solve the problem!! break;//0------1---------2---------3//synchronized (this) {//Put here also wrong!! May all hang up in the above judgment statement there!! In particular, this adds synchronization, a thread is locked, and the other threads are not coming in more easily hang here!! After the last 1 tickets were sold and then entered, there 0,-1,-2!!! Self-authentication: The only synchronization of the bottom sentence is not solve the problem, you can still hang in the sleep statement there, so the operation of the same resource of the multi-bar-language-sentence are synchronized, because a thread can only execute a partial statement, execution is taken away, causing the operation of the same resource thread security issues. The sleep statement is just to demonstrate that the execution of this multi-statement operation of the same resource is taken away (magnify the probability of this being taken, or the manual demo let it be taken away!) try {//left 1 tickets, all over the above judgment conditions here-------> I have a more serious situation here: (The teacher is to judge Tickets>0 when executed) because a few threads to wake up here, tickets into negative, Then again into the loop when found not 0, never end!! To make it easier to explain, change to <=0!! 0------1-------2--------3thread.sleep (10);} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Synchronized (this) {System.out.println (Thread.CurrentThread (). GetName () + "..." +tickets--);//}}}}}public class Ticketdemo {public static void main (string[] args) {Ticket ticket=new Ticket (); new Thread (Ticket). Start (); New Thread ( Ticket). sTart (); new thread (Ticket). Start (); New thread (Ticket). Start (); New thread (Ticket). Start ();}
Output Result: (partial example)
Thread-0 ... 100
Thread-2 ... 99
Thread-4 ... 98
Thread-1 ... 97
Thread-3 ... 96
Thread-0 ... 95
...
Thread-0 ... 25
Thread-2 ... 24
Thread-4 ... 23
Thread-1 ... 22
Thread-3 ... 21st
Thread-0 ... 20
Thread-2 ... 19
Thread-4 ... 18
Thread-1 ... 17
Thread-3 ... 16
Thread-0 ... 15
Thread-2 ... 14
Thread-4 ... 13
Thread-1 ... 12
Thread-3 ... 11
Thread-0 ... 10
Thread-2 ... 9
Thread-4 ... 8
Thread-1 ... 7
Thread-3 ... 6
Thread-0 ... 5
Thread-2 ... 4
Thread-4 ... 3
Thread-1 ... 2
Thread-3 ... 1
2. Bank Deposit: resolved thread safety issues
package Cn.xbai.thread;class bank{private int sum=0;public int add (int num) {return sum+=num;}} Class Cus implements Runnable{private Bank Bank=new Bank ();p ublic void Run () {//loop multiple times to see the meaning of multi-threaded tasks for (int i=0;i<3;i++) { I do not need synchronization, local variables, each thread has a synchronized (this) {//slow process, enlarge the contradiction, so the problem arises from the try {Thread.Sleep (ten);} catch (Interruptedexception E {//TODO auto-generated catch Blocke.printstacktrace ();} I don't understand how this is going to happen. Output two 100, the following should be two statements: System.out.println (Bank.add (100));} /**100100///Here The return value should be an independent result intermediate value, is the copy value of sum, and should be output after the addition, then the first thread should be the output has not been added, the second thread came in output and added, the first thread output 100, and then add? 2003004005005006007008009001000110012001300 *//**200100300500400600 will the results of this set of executions provide a reason? 700800900100011001200130014001500 */}}}public class Bankdemo {public static void main (string[] args) {Cus c=new Cus (); new Thread (c). Start ();//each person saves 300new thread (c). Start (); new Thread (c). Start (); new Thread (c). Start (); new Thread (c). Start () ;}}
Operation Result:
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
1500
3. Single-instance design pattern of lazy thread safety problem: A number of test points in the face (why there is a thread security problem, how to solve its thread safety problems, with what locks, how to improve the efficiency after synchronization ...) )!!
Package cn.xbai.thread;//Singleton design mode: A hungry man---------> No thread safety issue: The statement that operates a shared resource has only one sentence/*class single{private static final single s= New single ();//final represents immutable, static represents only one copy (and there is no dependent object, but there is only one object here) Private () {}public static a getinstance () { return s;}} *///Lazy: Delay Loading class Single{private static single s=null;//Note that this cannot be final, otherwise you cannot assign the private single () {}public static single GetInstance () {///plus double judgment, improve the efficiency of lazy synchronization, as long as the object is created, the outer if is not satisfied, there is no need to enter the synchronization code block (the process of determining the lock is inefficient) if (s = = null) {synchronized (single.class {//Note that the static method does not have this, the lock is a bytecode file Object!! if (s = = null) {//NOTE to judge! No need to create a blank! -------a---------Bs = new single ();//S is a shared data, lazy type in multi-threaded access will be a security risk: A separate mode new out of multiple objects!! Need to sync!! }}}return s;}} public class Singledemo {}
4. Deadlock:The cause of deadlock, write a deadlock program, how to avoid deadlock, interview Test center!!
Package Cn.xbai.thread;class Deadpool implements Runnable{public Boolean flag=true;public void Run () {if (flag==true) { while (true) {synchronized (Locks.lock_one) {System.out.println ("if LOCK One"); synchronized (locks.lock_two) { SYSTEM.OUT.PRINTLN ("if Lock");}}} Else{while (True) {synchronized (locks.lock_two) {System.out.println ("Else LOCK"); synchronized (Locks.lock_one) { SYSTEM.OUT.PRINTLN ("Else lock One");}}}}} Class Locks{public static Final Object Lock_one=new object ();p ublic static Final Object Lock_two=new object ();} Synchronous code block nesting, different locks, two threads each need each other to occupy the lock, causing the deadlock public class Deadlockdemo {public static void main (string[] args) {Deadpool deadpool= New Deadpool (); new Thread (Deadpool). Start (); try {thread.sleep ()} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();} Deadpool.flag=false;new thread (Deadpool). Start ();//As long as the same two locks are used, even if two threads execute a different implementation runnable the object will also appear this deadlock problem! This is not related to multi-threaded operation of the same resource!! }}//down to see the following execution results and analysis:/**if lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif LoCK Oneif Lock Twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif Loc K twoif Lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif Lock TWOIF Lock Oneif Lock Twoif Lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock TWOIF Lock Oneif Lock Twoif Lock Oneif Lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock TWOIF lock O Neif Lock Twoif Lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock TWOIF lock Oneif lock TW OIF lock Oneif Lock TWOIF lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif Lock One If lock Twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif Lock Twoi F Lock Oneif Lock Twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock TWOIF Lock Oneif Lock Twoif Lock Oneif LOck twoif Lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif Lo CK Oneif Lock Twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif lock twoif lock Oneif Loc K twoif Lock Oneif lock twoif lock Oneif lock twoif lock Oneif Lock Twoelse Lock-----------------------Result: Else lock lock t Wo,if lock One, they can no longer enter the inner layer, also no end, deadlock! If lock one * @author Administrator * */
[Java] Multithreading review (update not finished)