[Multithreading] Two threads take turns to print numbers 1-100, one for odd numbers and the other for even numbers, printing sequentially

In today’s Meituan Ermeng, I encountered this problem. I just remembered to understand the Fa for a while, but I didn’t write it out by hand.

Use the visibility of volatile to get some access to threads and make changes~

package mianTest;

// 单纯的利用boolean变量来写 加一个volatile关键字:保证他的可见性
public class Demo01 {
    
    
	volatile static int flag = 0;

	public static void main(String[] args) {
    
    
		Thread myThread = new Thread(new myThread1());
		Thread myThread2 = new Thread(new myThread2());
		myThread.start();
		myThread2.start();
	}

	public static class myThread1 implements Runnable {
    
    

		@Override
		public void run() {
    
    
			int i = 0;
			while (i < 10) {
    
    
				if (flag == 0) {
    
    
					System.out.println(Thread.currentThread().getName() + " = " + i);
					i += 2;
					flag = 1;
				}
			}
		}

	}

	public static class myThread2 implements Runnable {
    
    
		@Override
		public void run() {
    
    
			int i = 1;
			while (i < 10) {
    
    
				if (flag == 1) {
    
    
					System.out.println(Thread.currentThread().getName() + " = " + i);
					i += 2;
					flag = 0;
				}
			}

		}

	}
}

Guess you like

Origin blog.csdn.net/qq_40915439/article/details/108720266