1.1. Processes and Threads
Process: An application is generally a process, an ongoing program
Each process has at least one thread, and there is an execution order, which is an execution path or a control unit
Threads: A separate control unit in a process that controls the execution of a process.
Windows Task Manager can view the process, Linux under the PS command
The thread is the smallest unit of the process
Threads depend on processes
Threads die as the process is created and created, as the process ends
such as Thunderbolt: You can open multiple downloads at the same time, is multithreaded
Multiple programs are executed at the same time, when the CPU switches quickly, it looks as if it is executing at the same time, actually in the CPU switching.
The meaning of multithreading exists: You can let the contents of the program execute simultaneously.
Second, the creation of the inheritance thread
2.1. Inherit thread, rewrite the Run method
Package com.pb.thread.demo1;/** * * @author Denny * Inherit the thread class and override the Run method to create a threading class * */public class MyThread extends thread { private int count; / * Override the Run method * @see java.lang.thread#run () */ @Override public void Run () {/ * * The code block or method to run is called here, or it is written directly here * /while (count<10) { count++; System.out.println ("My thread Run method started" +count);} } public static void Main (string[] args) { //declares the thread class MyThread mt=new MyThread (); Start the thread, the JVM calls the Run method Mt.start (); Main thread for (int x=0;x<10;x++) { System.out.println ("main thread" +x); }} }
Multiple threads are in preemption of CPU execution, who Rob, who executes
At some point, there can only be one program running
The CPU is doing a quick switch to achieve the effect that appears to be running simultaneously.
Multithreading one feature: Randomness, who grabs who to execute.
Third, thread running and thread state
3.1. Call the Start () method
Causes the thread to start executing, and the Java Virtual machine calls the thread's run () method
Why do you want to override the Run method?
The thread class is used to describe threads.
This class defines a feature that stores the code that the thread wants to run. This storage function is the Run method.
In other words, the Run method in the thread class is used to store the code that the thread is running
If you call the run () method directly, it is the same as the normal method of invoking the object., just the object invocation method. The thread was created and not running.
Only start () can run the thread.
3.2. Thread Status
NEW: Create a thread, new thread () or subclass
Running: Running thread, calling the start () method
Freeze: Threads that have been created, but not running. Sleep (long milliseconds), wait () thread waits until notify () wakes up to run
Temporary status blocking: operational eligibility, but no execution right, is not yet switched to the CPU.
Extinction: The thread dies Stop (), or the thread runs complete.
Iv. Getting thread objects
4.1. Get the current thread object and name
Inherit thread class implementation threads, local variables have a separate copy cannot share data
Package com.pb.thread.demo1;/** * * @author Denny * inherits the thread class and overrides the Run method to create a threading class *thread.currentthread () to get the current thread object * Inherit thread class implementation threads, local variables have a separate copy cannot share data */public class MyThread extends thread {public MyThread (String name) { Super ( name); } / * Override the Run method * @see java.lang.thread#run () */ @Override public void Run () {/ * * To run the code block or method, call here, or write directly here */ for (int x=0;x<10;x++) { System.out.println ("My thread Run's name:" + Thread.CurrentThread (). GetName () + "," +x); } } public static void Main (string[] args) { //declares the thread class MyThread mt1=new MyThread ("MT1"); Mt1.setname ("Zhang San"); Set the thread name MyThread mt2=new MyThread ("mt2"); Start the thread, the JVM calls the Run method Mt1.start (); Mt2.start (); Main thread for (int x=0;x<10;x++) { System.out.println (CurrentThread (). GetName () + "," +x); }} }
Example:
Five, interface implementation thread
5.1. Implement Runnable interface
Override the Run method ()
The biggest benefit of implementing interfaces is the ability to share data
Example: Multi-window simultaneous ticketing,
Package com.pb.thread.demo1;/** * * @author Administrator multiple windows simultaneously sell tickets * */public class Ticket implements Runnable { c2/>private int tick = +; public void Run () {while (true) { if (tick > 0) { System.out.println (Thread.CurrentThread (). GetName () + " Sell: "+ tick--); } else{break ; }}} public static void Main (string[] args) { //declares the thread class Ticket ticket=new Ticket (); Create the thread object and make the class the parameter thread t1=new thread (ticket); T1.setname ("one window,"); Thread T2=new thread (ticket); T2.setname ("Window No. second,"); Thread T3=new thread (ticket); T3.setname ("Window No. third,"); Thread T4=new thread (ticket); T4.setname ("Window No. fourth,"); T1.start (); T2.start (); T3.start (); T4.start (); }}
Results:
Window No. 11th, Sell: 100 21st window, Sell: 98 31st window, Sell: 97 41st window, Sell: 96 51st window, Sell: 95 61st window, Sell: 94 72nd window, Sell: 99 82nd window, Sell: 92 91st window, sell: 93 10 A window, sell: 88 111th window, Sell: 87 121th window, sell: 86 132th window, sell: 89 142th window, Sell: 84 152th window, sell: 83 162th window, Sell: 82 172th window, Sell: 81 182th window, sell: 80 192th window, Sell: 79 No. No. 202 window, sell: 78 No. 212 window, Sell: 77 No. 222 window, sell: 76 No. 232 window, sell: 75 No. 242 window, sell: 74 No. 252 window, sell: 73 No. 262 window, sell: 72 No. 272 window, sell: 71 No. 282 window, Sell: 70 Window No. No. 292, Sell: 69 No. 302 window, sell: 68 No. 312 window, sell: 67 No. 322 window, sell: 66 No. 332 window, sell: 65 No. 342 window, sell: 64 No. 352 window, sell: 63 No. 362 window, sell: 62 No. 372 window, sell: 61 No. 382 No. window, Sell: 60 No. No. 392 window, sell: 59 No. 402 window, sell: 58 No. 412 window, sell: 57 No. 422 window, Sell: 56 No. 432 window, sell: 55 No. 442 window, sell: 54 No. 452 window, Sell: 53 No. 462 window, sell: 52 No. 472 window, Sell: 51 No. No. 482 window, sell: 50 No. 492 window, Sell: 49 No. 502 window, sell: 48 No. 512 window, sell: 47 No. 522 window, sell: 46 No. 532 window, sell: 45 No. 542 window, sell: 44 No. 552 window, sell: 43 No. 562 window, sell: 42 57 Window No. Second, sell: 41 No. 582 window, sell: 40 No. 592 window, sell: 39 No. 602 window, sell: 38 No. 612 window, sell: 37 No. 622 window, sell: 36 No. 632 window, sell: 35 No. 642 window, Sell: 34 No. 652 window, sell: 33 No. 662 # Window , Sell: 32 No. No. 672 window, sell: 31 No. 682 window, sell: 30 No. 692 window, sell: 29 No. 702 window, sell: 28 No. 712 window, sell: 27 No. 722 window, sell: 26 No. 732 window, sell: 25 No. 742 window, sell: 24 No. 752 window, sell: 23 Window No. No. 762, Sell: 22 No. 772 window, sell:21 No. No. 783 window, sell: 90 No. 794 window, sell: 91 No. 803 window, sell: 19 No. 812 window, sell: 20 No. 821 window, sell: 85 No. 832 window, sell: 16 No. 843 window, sell: 17 No. 854 window, sell: 18 No. 863 window, sell: 13 87 Window No. Third, sell: 11 No. 883 window, sell: 10 No. 893 window, sell: 9 No. 903 window, sell: 8 No. 913 window, sell: 7 No. 923 window, sell: 6 No. 933 window, sell: 5 No. 943 window, sell: 4 No. 953 window, sell: 3 No. 963 window, sell: 2 97 Window No. Third, sell: 1 No. 982 window, sell: 14 No. 991 window, Sell: 151,004th window, sell: 12
Two ways to create threads:
|
Advantages |
disadvantage |
inherit the thread class |
1. Write a simple 2. You can use th The IS keyword directly accesses the current thread |
Cannot inherit other classes Cannot implement data sharing |
implement runnable interface |
1. can inherit its It is class 2. You can use the same Runnable object 3 between multiple threads. You can share data |
programming is slightly more complex, if you want to access the current thread, Need to invoke the CurrentThread () method of the thread class &N Bsp , &NB Sp , &NB Sp |
VI. Thread SAFETY
6.1, or the above example
Plus sleep (1000) sleeps for 1 seconds
Package Com.day10.thread.demo1;public class Ticket implements Runnable { private int num=100; @Override public Void Run () { while (true) { if (num>0) { try { thread.sleep ( )}; Current thread sleeps 1 seconds, millisecond unit } catch (Interruptedexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + ", sell" +num--+ "ticket"); }} public static void Main (string[] args) { Ticket t=new Ticket (); Thread t1=new thread (t); Thread t2=new thread (t); Thread t3=new thread (t); Thread t4=new thread (t); T1.start (); T2.start (); T3.start (); T4.start (); }}
Results:
Picked up java_tool_options:-javaagent:/usr/share/java/jayatanaag.jar Thread-0, sell ticket No. 100th Thread-2, sell 99th ticket Thread-1, Sell 98th ticket Thread-3, sell 97th ticket Thread-0, sell 96th ticket Thread-2, sell 95th ticket Thread-1, sell 94th ticket Thread-3, sell 93rd ticket Thread-0, sell 92nd ticket Thread-2, Sell 91st ticket Thread-1, sell 90th ticket Thread-3, sell 89th ticket Thread-0, sell 88th ticket Thread-2, sell 87th ticket Thread-1, sell 86th ticket Thread-3, sell 85th ticket Thread-0, Sell 84th ticket Thread-2, sell 83rd ticket Thread-1, sell 82nd ticket Thread-3, sell 81st ticket Thread-0, sell 80th ticket Thread-2, sell 79th ticket Thread-1, sell 78th ticket Thread-3, Sell 77th ticket Thread-0, sell 76th ticket Thread-2, sell 75th ticket Thread-1, sell 74th ticket Thread-3, sell 73rd ticket Thread-0, sell 72nd ticket Thread-2, sell 71st ticket Thread-1, Sell 70th ticket Thread-3, sell 69th ticket Thread-0, sell 68th ticket Thread-2, sell 67th ticket Thread-1, sell 66th ticket Thread-3, sell 65th ticket Thread-0, sell 64th ticket Thread-2, Sell 63rd ticket Thread-1, sell 62nd ticket Thread-3, sell 61st ticket Thread-0, sell 60th ticket Thread-2, sell 59th ticket Thread-1, sell 58th ticket Thread-3, sell 57th ticket Thread-0, Sell 56th ticket Thread-2, sell 55th ticket Thread-1, sell 54th ticket Thread-3, sell 53rd ticket Thread-0, sell 52nd ticket Thread-2, sell 51st ticket Thread-1, sell 50th ticket Thread-3, Sell 49th Ticket Thread-0, sell 48th ticket Thread-2, sell 47th ticket Thread-1, sell 46th ticket Thread-3, sell 45th ticket Thread-0, sell 44th ticket Thread-2, sell 43rd ticket Thread-1, Sell Ticket No. 42nd Thread-3, sell 41st Thread-0, sell 40th Thread-2, sell 39Ticket Thread-1, sell ticket No. 38th Thread-3, sell 37th ticket Thread-0, sell 36th ticket Thread-2, sell 35th ticket Thread-1, sell 34th ticket Thread-3, sell 33rd ticket Thread-0, Sell 32nd Ticket Thread-2, sell 31st ticket Thread-1, sell 30th ticket Thread-3, sell 29th ticket Thread-0, sell 28th ticket Thread-2, sell 27th ticket Thread-1, sell 26th ticket Thread-3, Sell 25th Ticket Thread-0, sell 24th ticket Thread-2, sell 23rd ticket Thread-1, sell 22nd ticket Thread-3, sell 21st ticket Thread-0, sell 20th ticket Thread-2, sell 19th ticket Thread-1, Sell 18th ticket Thread-3, sell 17th ticket Thread-0, sell 16th ticket Thread-2, sell 15th ticket Thread-1, sell 14th ticket Thread-3, sell 13th ticket Thread-0, sell 12th ticket Thread-2, Sell 11th ticket Thread-1, sell 10th ticket Thread-3, sell 9th ticket Thread-0, sell 8th ticket Thread-2, sell 7th ticket Thread-1, sell 6th ticket Thread-3, sell 5th ticket Thread-0, Sell 4th Ticket Thread-2, sell 3rd ticket Thread-1, sell 2nd ticket Thread-3, sell 1th ticket Thread-0, sell No. 0 ticket Thread-2, sell-1th ticket Thread-1, sell-2nd ticket
I found out that we sold more tickets.
Why? Because the current thread sleeps for 1 seconds, the other thread can sell the ticket,
Condition Check 1>0, if 4 people check at the same time, the condition is set up, continue to sell tickets appeared, negative
How to solve? Feed Line Cheng
causes of thread safety problems:
1. Multiple threads are manipulating the shared data.
2. There are several threads in the thread code that manipulate shared data.
When a thread executes multiple code operations that share data, other threads participate in the operation, causing thread safety problems.
The workaround is to encapsulate the thread code that has multiple operations sharing data, and when the thread executes the code, the other threads are not allowed to participate in the operation. It is necessary for the other threads to participate in the operation when the code is executed by the front-end thread.
Look at the sync synchronized below
Vii. Synchronizing code blocks
7.1, synchronized
Format of the synchronized code block:
Synchronized (object) {
Code that needs to be synchronized;
}
Benefits of synchronization: Resolves thread security issues.
The disadvantage of synchronization: When the thread is quite a long time, because each thread will judge the synchronization of the lock, this is very resource-intensive, virtually reduce the program's operational efficiency.
Prerequisites for synchronization: There must be multiple threads and use the same lock.
Modify the above code
Package Com.day10.thread.demo1;public class Ticket implements Runnable { private int num=100; @Override public Void Run () {while (true) { synchronized (this) { if (num>0) { try { Thread.Sleep (+); Current thread sleeps 1 seconds, millisecond unit } catch (Interruptedexception e) { e.printstacktrace (); } System.out.println (Thread.CurrentThread (). GetName () + ", sell" +num--+ "ticket"); else{break ; }}} public static void Main (string[] args) { Ticket t=new Ticket (); Thread t1=new thread (t); Thread t2=new thread (t); Thread t3=new thread (t); Thread t4=new thread (t); T1.start (); T2.start (); T3.start (); T4.start (); }}
Eight, synchronous function
8.1. Synchronization method
Package Com.day10.thread.demo2;public class Account {//balance private double blance=500; Withdrawal public void withdraw (int num) {blance=blance-num; } public double Getblance () {return blance; } public void Setblance (double blance) {this.blance = blance; }}package Com.day10.thread.demo2;public class Accountthread implements Runnable {private account account=new A Ccount (); @Override public void Run () {for (int i = 0; i < 5; i++) {if (account.getblance () <0) { SYSTEM.OUT.PRINTLN ("Overdrawn!!!"); } makwithdraw (100); The method of withdrawing 100}/* * * */public void makwithdraw (int num) {//Determine if the balance is greater than the number to be withdrawn (Account.getblance () >=num) {System.out.println (Thread.CurrentThread (). GetName () + ": Ready to withdraw money!"); try {thread.sleep (1000);//wait 1 seconds account.withdraw (num);System.out.println (Thread.CurrentThread (). GetName () + ": Withdrawals completed!, the current balance is:" +account.getblance ()); } catch (Interruptedexception e) {e.printstacktrace (); }}else{System.out.println (Thread.CurrentThread (). GetName () + "The balance is not sufficient to cover the current withdrawal, the balance is : "+account.getblance ()); }}}package Com.day10.thread.demo2;public class Demo {public static void main (string[] args) {Accou Ntthread at=new Accountthread (); Thread T1=new thread (at); T1.setname ("Zhang San"); Thread T2=new thread (at); T2.setname ("Zhang San Wife"); T1.start (); T2.start (); }}
Results:
Zhang San: ready to withdraw! Zhang San Wife: Prepare to withdraw money! Zhang San: withdrawal is complete!, the current balance is: 400.0 Zhang three: Prepare to withdraw money! Zhang San Wife: The withdrawal is complete!, the current balance is: 300.0 three wives: Ready to withdraw money! Zhang San: Withdrawals complete!, the current balance is: 200.0 three: ready to withdraw! Zhang San Wife: The withdrawal is complete!, the current balance is: 100.0 three wives: Ready to withdraw money! Zhang San: withdrawal is complete!, the current balance is: 0.0 Three balances are insufficient to cover the current withdrawal, the balance is: 0.0 three balances are insufficient to cover the current withdrawal, the balance is: 0.0 Three wives: withdrawals complete!, the current balance is:-100.0 overdrawn!! Zhang San wife balance is insufficient to pay the current withdrawal, the balance is: -100.0 overdrawn!! Zhang San wife balance is insufficient to cover the current withdrawal, the balance is: -100.0
Plus sync keyword
/* * Withdrawal Method * /public synchronized void makwithdraw (int num) { //To determine if the balance is greater than the number to be withdrawn if ( Account.getblance () >=num) { System.out.println (Thread.CurrentThread (). GetName () + ": Ready to withdraw money!"); try { thread.sleep (1000);//wait 1 seconds account.withdraw (num); System.out.println (Thread.CurrentThread (). GetName () + ": Withdrawal is complete!, the current balance is:" +account.getblance ()); } catch (Interruptedexception e) { e.printstacktrace (); } } else{ System.out.println (Thread.CurrentThread (). GetName () + "The balance is not sufficient to cover the current withdrawal, the balance is: " + Account.getblance ()); } }
Results:
Zhang San: ready to withdraw money! Zhang San: withdrawal is complete!, the current balance is: 400.0 three wives: Ready to withdraw money! Zhang San Wife: Withdrawals completed!, the current balance is: 300.0 three: Prepare to withdraw money! Zhang San: Withdrawals completed!, the current balance is: 200.0 three: Ready to withdraw money! Zhang San: withdrawal complete! : 100.0 Three: Prepare to withdraw money! Zhang San: the withdrawal is complete!, the current balance is: 0.0 Three balances are insufficient to cover the current withdrawals, the balance is: 0.0 three wives balance is insufficient to cover the current withdrawal, the balance is: 0.0 three Wives The balance is insufficient to cover the current withdrawal, the balance is: 0.0 three wives ' balance is insufficient to cover the current withdrawal, the balance is: 0.0 three wives balance is insufficient to pay the current withdrawal, the balance is: 0.0
No overdraft occurred
Synchronizing code blocks:
/* * Withdrawal Method * /public void Makwithdraw (int. num) { synchronized (account) { ///Determine if the balance is greater than the number to be withdrawn if (account.getblance () >=num) { System.out.println (Thread.CurrentThread (). GetName () + ": Ready to withdraw money!"); try { thread.sleep (1000);//wait 1 seconds account.withdraw (num); System.out.println (Thread.CurrentThread (). GetName () + ": Withdrawal is complete!, the current balance is:" +account.getblance ()); } catch (Interruptedexception e) { e.printstacktrace (); } } else{ System.out.println (Thread.CurrentThread (). GetName () + "The balance is not sufficient to cover the current withdrawal, the balance is: " + Account.getblance ());}}}
As a result, no overdraft occurred
the difference between a synchronization function and a synchronous code block:
1. The lock of the sync function is a fixed this.
2. The lock of the synchronization code block is an arbitrary object.
It is recommended that you use synchronous code blocks.
Because the lock of the synchronization function is fixed this, the lock of the synchronous code block is arbitrary object, then if the synchronous function and the synchronous code block use this as the lock, the synchronization can be implemented.
Nine, synchronous lock
9.1, the same lock
Synchronous method synchronization objects are this, and synchronous code blocks can also use this to synchronize
Ten, static synchronization
10.1. Static synchronization
This is not possible because the this is not defined in a static method
Static into memory, there is no such object in memory, but there must be a corresponding bytecode file object for that class
A static synchronization function uses a lock that is the byte-code file object that the function belongs to, can be obtained using the GetClass method, or it can be represented by the current class name. class.
Synchronizid (class name. Class) {or object. getclass
}
Xi. single-mode plus synchronous lazy
11.1, lazy-type plus lock
Package com.day10.thread.demo2;/** * * @author Denny * Singleton mode * A hungry man type, there is no problem of rebirth into object * Lazy worker, plus synchronize */public class Singledemo { private static Singledemo Singledemo; Private Singledemo () { } public static Singledemo getnewintance () { if (singledemo==null) {//judgment is not empty, Not empty directly return, is empty on lock synchronized (singledemo.class) { //locking//this.getclass () Direct Write Object Singledemo.getclass () also line if (singledemo==null) { singledemo=new singledemo ();}} } return Singledemo;} }
12. Deadlock
12.1. One of the common scenarios of deadlocks: synchronization of nesting.
Class mylock{Static Object Locka=new object (); Static Object Lockb=new object ();} public class Demo implements Runnable {private Boolean flag; Public Demo (Boolean flag) {This.flag = flag; } @Override public void Run () {if (flag) {while (true) {Synchron Ized (Mylock.locka) {System.out.println ("If.........locka"); Synchronized (mylock.lockb) {System.out.println ("if.........lockb"); }}}} and else {while (true) {synchronized ( MYLOCK.LOCKB) {System.out.println ("else.........lockb"); Synchronized (Mylock.locka) {System.out.println ("Else.........locka"); }}}}} public static void Main (string[] args) {ThreadT1 = new Thread (new Demo (true)); Thread t2 = new Thread (new Demo (false)); T1.start (); T2.start (); }}
Recommended object to be locked, declared as static
Basic Learning day11--Multithreading thread creation, operation, synchronization and lock