Why use Multithreading:
Single thread can only do one thing and multi-threaded to do a lot of things at the same time (put the task into the thread to perform high efficiency)
And the so-called simultaneous dry is not the real sense at the same time just (this is called CPU) CPU in each thread randomly switch to perform the work in the thread
Multithreaded writing:
1) The first type: (Thread Class)
Class STU1 extends thread{
Overriding the Run method
}
Call: Stu1 su = new Stu1 ();
Su.start ()//internal automatically calls the Run method to put the run method on the thread call
2) The second type: General Task Class (because the first type can only be single-inheritance can not be implemented to inherit the other parent class and inherit the thread class so the first method of extensibility is poor)
Create thread object lines directly Chengneigan things into a custom object implementation (in the modified design mode)
Underlying code
Class thread{
Private Runnable R
public void Thread (Runnable r) {//use a parameter construct to pass in a custom object
THIS.R = R;
}
public void Start () {
R.run ();
}
}
Class Stu implements runnable{} The Run method that implements the underlying start invocation of the interface thread class is actually the run method in our custom class
Thread th = new Thread (new Stu ())//Create threaded object directly
Th.start ();
We use the second method to create multithreading as follows:
public static void Main (string[] args) {//different line Cheng Gan the same thing salewindow SW = new Salewindow (); thread T1 = new Thread (SW); Thread t2 = new Thread (SW), T1.setname ("Window A"), T2.setname ("Window B"); T1.start (); T2.start ();}
public class Salewindow implements Runnable {private int ticketcount = ten; @Overridepublic void Run () {//TODO Auto-generat Ed method stub//Multiple Windows sell ticket for (int i = 0;i<10;i++) {if (ticketcount>0) {//string concatenation information variable + "" You can stitch into string System.out.println (Thread.CurrentThread (). GetName () + "sell" +ticketcount+ "ticket"); Ticketcount--;try { Thread.Sleep (500);} catch (Interruptedexception e) {//TODO auto-generated catch Block//e.printstacktrace ();}}}}
Final result diagram:
From the results of the operation: the same ticket was sold to two people. This is not allowed in real life this can lead to thread safety issues.
There are three elements that have a thread safety problem that must be met at the same time to produce thread safety:
1. Must have shared resources
2, must be multi-threaded environment
3. Shared resources are available for each thread
The above example: The ticket is a shared resource, is a multithreaded environment, the thread executes the task and uses the shared resources, so it will lead to thread safety
How do I fix thread safety?
The core of solving thread safety is to give a lock (synchronous lock) to a task in one thread, and this time the JVM will have to wait until the code in this task finishes executing another line thread.
Two ways:
1. Synchronous code block:
public class Salewindow implements Runnable {private int ticketcount = ten; @Overridepublic void Run () {//TODO Auto-generat Ed method stub//Multiple window ticket for (int i = 0; i < i++) {//can be arbitrarily set lock synchronized (this) {if (Ticketcount > 0) {//string concatenation information Variable + "" can be stitched into string System.out.println (Thread.CurrentThread (). GetName () + "sell" + Ticketcount + "Ticket"); Ticketcount--;try { Thread.Sleep (500);//Every 500 milliseconds the thread sleeps and then automatically wakes itself (in order to adjust the thread speed)} catch (Interruptedexception e) {//TODO auto-generated catch block//e.printstacktrace ();}}}}}
2. Synchronization method:
public class Salewindow implements Runnable {private int ticketcount = 10; The default pinned lock object this
Wrap the thread-safe code into a method and set it to a synchronous method public synchronized void Syncb () {if (Ticketcount > 0) {//string concatenation information variable + "" can be stitched into a string system.out . println (Thread.CurrentThread (). GetName () + "sell" + Ticketcount + "Ticket"); ticketcount--;try {thread.sleep;} catch ( Interruptedexception e) {//TODO auto-generated catch block//e.printstacktrace ();}}} @Overridepublic void Run () {//TODO auto-generated method stub//multiple Windows sell ticket for (int i = 0; i <; i++) {SYNCB ();}}}
Result diagram:
The final result is that each window cannot sell the same ticket. Resolves thread safety issues
Communication between threads
(PS: Communication between threads and thread safety is not related to both)
How can I get two threads to communicate with each other?
Threads are independent of each other and the real communication is through the middleware (the synchronization lock must be the same lock) to achieve the purpose of communication between the threads
Case: Two threads alternating the output of a single piece of data (meaning that you have to follow the rules of what I say you say)
Class BINGB extends Thread {public void run () {for (int i = 0;i<5;i++) {System.out.println ("ice-cold beauty, such as Flower Ugliness");}} Class RuH extends Thread{public void Run () {for (int i = 0;i<5;i++) {System.out.println ("Flower beauty, Ice ice Ugliness");}} public class Test {public static void main (string[] args) {BINGB bb = new BINGB (); RuH RH = new RuH (); Bb.start (); Rh.start ();}}
Result diagram: This result is not an alternate occurrence
To achieve the alternate purpose code is as follows:
Class Mylock{static Object o = new Object ();} Class BINGB extends Thread {public void run () {for (int i = 0;i<5;i++) {// Locking (meaning that the code of another thread must wait until the task code of this thread has been executed) synchronized (MYLOCK.O) {System.out.println ("ice-cold beauty, such as flowers Ugly"); Mylock.o.notify ();//Wake up another thread (represented here as a flower thread) try {mylock.o.wait ();//temporarily completely hibernate this thread (does not automatically wake up need to manually wake up) while unlocking the blocking thread code will not go down the JVM switches to another thread} catch (Interruptedexception e) {//TODO auto-generated catch Block}}}}}class RuH extends Thread{pub LIC void Run () {for (int i = 0;i<5;i++) {synchronized (MYLOCK.O) {System.out.println ("Flower beauty, Ice ice ugliness"); Mylock.o.notify ();//Wake up another thread (shown here as Ice Ice) try {mylock.o.wait ();//temporarily completely hibernate this thread while unlocking the blocking thread} catch ( Interruptedexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}} public class Test {public static void main (string[] args) {BINGB bb = new BINGB (); RuH RH = new RuH (); Bb.start (); Rh.start ();}}
Multi-threaded status Flowchart:
Write here about the thread of the basic explanation, if the content has my own understanding of the wrong place also please the Great god advice, little brother hesitate to ask!
Java Multithreading and Thread safety