Java多线程,两个线程交替打印

Java多线程,两个线程交替打印(jdk 1.8)

public class AlternatePrint {
	
	public static int i = 0;
    
    public static boolean falg = false;
    
    public static Object lock = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (falg) {
                synchronized (lock) {
                		falg = false;
                        System.out.println(Thread.currentThread().getName() + " i = " + i++);
                        lock.notify();
                        try {
                            lock.wait();
                            Thread.sleep(1000);
                        }
                        catch (InterruptedException e) {
                        }
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            while (!falg) {
                synchronized (lock) {
                		falg = true;
                        System.out.println(Thread.currentThread().getName() + " i = " + i++);
                        lock.notify();
                        try {
                            lock.wait();
                            Thread.sleep(1000);
                        } 
                        catch (InterruptedException e) {
                        }
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}

打印结果
此处是打印结果

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页