We all know that the code form of the thread in Java can be written as follows
New Thread (New Runnable () {@Overridepublic void Run () {//TODO auto-generated Method stub}}). Start ();
Under Multi-threaded startup, the running between the threads will be randomly switched, usually sometimes, we may need the business requirements of the orderly switch between the execution, to ensure business quasi-cutting, such as the bank pick-up machine, as well as train tickets, in this case, we want to control the communication between the threads, Need to be implemented by a synchronous lock
For example I want thread A to execute 5 thereafter, thread B executes 10 times, or vice versa, so 50 times.
Now let's look at the code
Class business{ Private Boolean bshouldsub = true; Public synchronized void Sub (int. i) { while (!bshouldsub) {try {this.wait ()} catch (Interruptedexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}} for (int j=0;j<=i;j++) {System.out.println ("Sub Thread------------------------------------------------------------"+j);} Bshouldsub = false; This.notify (); synchronized void Main (int i) { while (bshouldsub) {try {this.wait ()} catch (Interruptedexception e) {// TODO auto-generated catch Blocke.printstacktrace ();}} for (int j = 0; J <= I; j + +) {System.out.println ("main thread sequence of " + j+ " i=" + i);} Bshouldsub = True;this.notify (); } }
Separate the business of proportionality into one class to ensure the uniqueness of the lock.
Private Boolean bshouldsub = true; is for communication between threads.
Let's look at the execution code of the thread
Final Business business = new Business (), New Thread (new Runnable () {@Overridepublic void Run () {for (int i=0;i<=50;i++) { Business.sub (5);}}). Start (); for (int i = 0; I <=; i++) {business.main (10);}}
At this point, it must be a beginner's understanding of the thread communication mechanism will be further
Synchronous communication between threads