【多线程】两个线程轮流打印数字1-100,一个打奇数一个打偶数,顺序打印

在今天的美团二面中,遇到了这个问题,一时间只想起来了解法,手写没有写出来

利用volatile的可见性,来对于线程进行一些获取,进行改变~

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;
				}
			}

		}

	}
}

猜你喜欢

转载自blog.csdn.net/qq_40915439/article/details/108720266