Java两个线程交替打印奇偶数

package juc;

public class Printer {

	private volatile int i = 0;

	public synchronized void printA() {
		while (i < 100) {
			try {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				i++;
				notifyAll();
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

	public synchronized void printB() {
		while (i < 100) {
			try {
				System.out.println(Thread.currentThread().getName() + ":" + i);
				i++;
				notifyAll();
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}

	public static void main(String[] args) {
		Printer printer = new Printer();
		new Thread(() ->{
				printer.printA();
			}).start();

		new Thread(() ->{
			printer.printA();
		}).start();
	}
}

 

你可能感兴趣的:(Java&Javaweb)