Synchronized multi-threading

The information in the Java heap is shared. The thread copies the information in the heap, operates on the copy, and then synchronizes the information in the heap after the operation. The information in the heap may be modified by the b thread, and the copy of the a thread is still not. Before the modification, it will cause multiple concurrency problems at this time. To solve the problem of multi-concurrency is to turn the original parallel execution program of multiple threads into a serial execution program of multiple threads through shackles.

example;

Please write 2 threads, thread 1 sequentially outputs odd numbers such as 1, 3, 5, ..., 99, and each number is one.

Thread 2 sequentially outputs even numbers such as 2, 4, 6...100, one for each.

The final result requirement is that the output is in natural order: 1, 2, 3, 4, ... 99, 100.

public class TestLock2 implements Runnable {
	private int num;

	private int initNum;

	public TestLock2(int num, int initNum) {
		this.num = num;
		this.initNum = initNum;
	}

	@Override
	public void run() {
		synchronized (this) {
			while (initNum < num) {
				this.notify();
				System.out.println(Thread.currentThread().getName() + ":" + initNum);
				initNum ++;
				try {
					this.wait();
				} catch (InterruptedException e) {
					e.printStackTrace ();
				}
			}
		}

	}

	public static void main(String[] args) { 
         //Print one hundred numbers, two threads loop 50 times, both are constructed with the instance of testLock2, and the global variables in testLock2 are shared TestLock2 testLock2 = new TestLock2(51, 1); Thread thread1 = new Thread(testLock2); thread1.setName("Thread 1"); Thread thread2 = new Thread(testLock2); thread2.setName("Thread 2"); thread1.start(); try { thread1.sleep(100); } catch (InterruptedException e) { e.printStackTrace (); } thread2.start(); } }

  

 

Guess you like

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