java multithreading

Java multi-threaded operation, for specific operations, the business code should be operated as a business class. In the business class, the mutually exclusive synchronization operation of the thread is performed. Specifically look at the following example:

package test.client;

public class Test2018 {
	public static void main(String[] args) {
		final ThreadTask threadTask = new ThreadTask();//Business task object
		new Thread(new Runnable() {
			@Override
			public void run() {
				for(int i=0;i<50;i++){
					threadTask.loopTask();//Sub thread task
				}
			}
		}).start();
		for(int i=0;i<50;i++){
			threadTask.mainTask();//Main thread task
		}
	}
}

class ThreadTask{
	private boolean flag = true;//Main thread, child thread running flag
	public synchronized void loopTask() {
		while(!flag){//Prevent thread false wakeup
			try {
				this.wait();//Thread waiting
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		for(int i=1;i<=100;i++) {
			System.out.println("Sub thread execution: "+i);
		}
		flag = false;
		this.notify();//Wake up the thread
	}
	public synchronized void mainTask() {
		while(flag){
			try {
				this.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		for(int i=1;i<=50;i++) {
			System.out.println("Main thread execution: "+i);
		}
		flag = true;
		this.notify();
	}
}

 Note: Ordered communication between two threads requires threads to wait and wake up.

For example, if a thread is waiting, it can be woken up by another thread, or it can wake up by itself (pseudo wakeup). We can set a private variable between two threads. Whether it is awakened or pseudo-awakened by itself, we will check this variable and execute our own code, which will become very safe.

Each business method will be added with synchronized so that the instance of the method will be locked like an object.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326344651&siteId=291194637