多线程交替打印

来自姬鸿昌的知识库
Jihongchang讨论 | 贡献2024年7月6日 (六) 12:22的版本
跳到导航 跳到搜索

https://www.bilibili.com/video/BV1ez421C7Fz/?spm_id_from=333.999.0.0&vd_source=92b1acbb084e38873b05857f8f1b9289

有两个线程,分别打印a字符和b字符

package basic;

import java.util.concurrent.atomic.AtomicInteger;

public class MultiPrint2 {

	public static void main(String[] args) throws InterruptedException {
		Object monitor = new Object();
		AtomicInteger i = new AtomicInteger(0);
		PrintRunnable pr = new PrintRunnable(monitor, i, 100);
		Thread t1 = new Thread(pr);
		Thread t2 = new Thread(pr);
		t1.start();
		t2.start();
		//得t1和t2都执行完才能结束
		t1.join();
		System.out.println(t1.getId() + "结束");
		//得t1和t2都执行完才能结束
		t2.join();
		System.out.println(t2.getId() + "结束");
	}
}

class PrintRunnable implements Runnable {
	private Object monitor;
	private AtomicInteger i;
	private int end;
	/**
	 * @param monitor
	 * @param i
	 * @param end
	 */
	public PrintRunnable(Object monitor, AtomicInteger i, int end) {
		super();
		this.monitor = monitor;
		this.i = i;
		this.end = end;
	}
	@Override
	public void run() {
		long id = Thread.currentThread().getId();
		synchronized (monitor) {
			while (i.get() < end) {
				System.out.println(id + ":" + i.incrementAndGet());
				try {
					monitor.notify();
					monitor.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				/**
				 * notify要在synchronized里,不然会抛IllegalMonitorStateException
				 * 这单独的一个notify调用是为了通知另一个还在while里wait的线程
				 */
				monitor.notify();
			}
		}
	}
}