In the previous article, we explained the mutex technology between threads, using the keyword synchronize to implement mutually exclusive techniques between threads. Depending on the business situation, we can choose a mutually exclusive method to implement mutually exclusive calls between threads. For example: A custom object implements a mutex (Synchronize ("custom Object") {}), the same class instance object (Synchronize (this) {}), and the class's Bytecode object (synchronize (bytecode object) {}). These three methods can realize mutual exclusion between threads, and we use it flexibly in practical application.
The following goes to today's topic: threading--the synchronous communication technology between threads; We also use the code in the Preach Intelligence podcast as an example to illustrate that a child thread runs 10 times, the main thread runs 10 times, and so alternately runs 50 times.
First look at the problem code when the synchronization technology is not applicable:
public static void Main (string[] args) {new Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {f The or (int j=1;j<=10;j++) {System.out.println ("Child Thread:" +thread.currentthread (). GetName () + "runs the" +i+ "times, repeats the" +j+ "Time");}}}). Start (); for (int. i=1;i<=50;i++) {for (int j=1;j<=10;j++) {System.out.println ("Main thread:" +thread.currentthread (). GetName () + "Run section" +i+ ", repeat" +j+ ");}}
The running result of the above code shows that the sub-thread and the main thread are running in a haphazard way, which obviously can't meet my requirements. Let's make a little adjustment. The code is as follows:
public class Threadsynchronizedtechnology {public static void main (string[] args) {new Thread (new Runnable () {@Overridepu Blic void Run () {for (int i=1;i<=50;i++) {
Use the byte code of the class as a mutex synchronized (Threadsynchronizedtechnology.class) {for (int j=1;j<=10;j++) {System.out.println (" Child thread: "+thread.currentthread (). GetName () +" runs the "+i+" times, repeats the "+j+" Time ");}}}). Start (); for (int. i=1;i<=50;i++) {synchronized (Threadsynchronizedtechnology.class) {for (int j=1;j<=10;j++) { System.out.println ("Main thread:" +thread.currentthread (). GetName () + "Run section" +i+ "Times, repeat" +j+ "Times");}}}}
The above code we use the class bytecode as a mutex, it is clear that the program is no longer cluttered run, the sub-thread and the main thread can complete the run, but did not implement our requirements of the alternate operation, do not hurry me to adjust, I very much like Zhang Xiaoxiang teacher Step-by-step teaching method (I am not, is from the heart), Let's proceed with the following adjustments:
public class Threadsynchronizedtechnology {public static void main (string[] args) {final Songzl song = new Songzl (); new Th Read (new Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {song.sub (i);}}). Start (); for (int i=1;i<=50;i++) {song.main (i);}}} Class songzl{//Child thread Run method public void sub (int i) {synchronized (Songzl.class) {for (int j=1;j<=10;j++) { SYSTEM.OUT.PRINTLN ("Child Thread:" +thread.currentthread (). GetName () + "Run the" +i+ "times, repeat the" +j+ "Times");}} The main thread runs the method public void main (int i) {synchronized (Songzl.class) {for (int j=1;j<=10;j++) {System.out.println ("main thread:" + Thread.CurrentThread (). GetName () + "Run the" +i+ "times, repeat the" +j+ "Times");}}}
Printing results are still not alternately run, I tuned to reflect the programming of the object-oriented thinking, the associated method encapsulated in the same class, convenient code operations. We then adjust the code:
public class Threadsynchronizedtechnology {public static void Main (string[] args) {final Songzl song = new Songzl (); New Thread (New Runnable () {@Overridepublic void Run () {for (int i=1;i <=50;i++) {song.sub (i);}}}). Start (); for (int i=1;i<=50;i++) {song.main (i);}}} Class songzl{//implements thread synchronous communication, mutually exclusive methods share the secondary variable private Boolean Jiaoti = true;//Child Threads Run the method: The method is mutually exclusive in the same class, similar to synchronized (this) {}public synchronized void sub (int i) {if (!jiaoti) {try {this.wait ()} catch (Interruptedexception e) {e.printstacktrace ()}} for (int j=1;j<=10;j++) {System.out.println ("Child Thread:" +thread.currentthread (). GetName () + "runs the" +i+ "times, repeats the" +j+ "Time");} Jiaoti = False;this.notify ();} The main thread runs the method: The method in the same class is mutually exclusive, similar to synchronized (this) {}public synchronized void main (int i) {if (Jiaoti) {try {this.wait ();} catch (Interruptedexception e) {E.printstacktrace ();}} for (int j=1;j<=10;j++) {System.out.println ("Main thread:" +thread.currentthread (). GetName () + "Run section" +i+ "Times, repeat" +j+ "Times");} Jiaoti = True;this.notify ();}}
Printing results are visible, has implemented the sub-thread and the main thread of the orderly alternating operation, the thread can be mutually exclusive, while simultaneously can synchronize the communication operation; The mutual exclusion of threads is implemented through synchronized, and the synchronous communication between threads is implemented by two threads that hold a variable together. However, the thread has a "false wake" situation, although the occurrence rate is low, but we can not ignore, continue to adjust the code:
public class Threadsynchronizedtechnology {public static void main (string[] args) {final Songzl song = new Songzl (); new Th Read (new Runnable () {@Overridepublic void Run () {for (int i=1;i<=50;i++) {song.sub (i);}}). Start (); for (int i=1;i<=50;i++) {song.main (i);}}} Class songzl{//implements thread synchronous communication, mutually exclusive methods share the secondary variable private Boolean Jiaoti = true;//Child Threads Run the method: The method is mutually exclusive in the same class, similar to synchronized (this) {}public synchronized void sub (int i) {//Avoids false wake of thread while (!jiaoti) {try {this.wait ();} catch (Interruptedexception e) { E.printstacktrace ();}} for (int j=1;j<=10;j++) {System.out.println ("Child Thread:" +thread.currentthread (). GetName () + "runs the" +i+ "times, repeats the" +j+ "Time");} Jiaoti = False;this.notify ();} The main thread runs the method: The method in the same class is mutually exclusive, similar to synchronized (this) {}public synchronized void main (int i) {//avoids the thread's false wake while (Jiaoti) {try { This.wait ();} catch (Interruptedexception e) {e.printstacktrace ();}} for (int j=1;j<=10;j++) {System.out.println ("Main thread:" +thread.currentthread (). GetName () + "Run section" +i+ "Times, repeat" +j+ "Times");} Jiaoti = True;this.notify ();}}
We use a while loop to avoid this false wake, and when the CPU is wayward to wake itself up to the wrong thread, or the thread neuropathy itself, we can use the while loop to avoid the situation. Well, so far, the code has completely met our needs. By using the code above, we can easily understand the synchronization and mutex techniques between threads.
Summary: What are the constraints between threads?
When a thread executes concurrently, the following two constraints exist between use threads due to resource sharing and thread collaboration.
(1) indirect mutual restriction. Multiple threads in a system must share some system resources, such as shared CPUs, shared I/O devices, and so-called indirect mutual constraints originate from this sharing of resources, and printers are the best examples, while thread a waits for other threads to use the printer.
(2) direct mutual restriction. This restriction is mainly due to the co-operation between threads, such as thread A, which provides the result of the calculation to thread B for further processing, and threads B will be in a blocked state before the data is delivered.
Indirect mutual restriction can be called mutual exclusion , direct mutual restriction can be called synchronization , for mutual exclusion can be understood, thread A and thread B mutually exclusive access to a resource, they will produce a sequential problem--or thread A waits for thread B to finish, Either thread B waits for the thread to finish, which is actually the thread synchronization. So synchronization includes mutual exclusion, and mutual exclusion is actually a special kind of synchronization .
Thread--java thread Synchronous communication technology