Synchronous communication between threads and synchronous communication between threads
We all know that the thread code in java can be written as follows:
new Thread(new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stub}}).start();
Under multi-thread startup, the running between threads will be switched randomly. Generally, we may need to switch between threads in an orderly manner in terms of service requirements, ensure business accuracy, such as bank ticketing machines and train ticketing. In this case, we need to implement synchronization locks to control inter-thread communication.
For example, I want thread a to execute 5 and then thread B to execute 10 times, or vice versa, so 50 times.
Next 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(); } public 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(); } }
Extract the business to be executed as a separate class to ensure the uniqueness of the lock.
Private boolean bShouldSub = true; it is used for communication between threads.
Next let's look at the thread Execution Code
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 <= 50; i++) {business.main(10);}}
At this point, I am sure that beginners will have a better understanding of the thread communication mechanism.