两个线程交替打印

两个线程交替打印

两个线程交替打印出 A:1 B:1 A:2 B:2 A:3 B:3

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource {
	private int num = 1;
	private Lock lock = new ReentrantLock();
	private Condition conditionA = lock.newCondition();
	private Condition conditionB = lock.newCondition();

	public void print3a(int r) {
		lock.lock();
		try {
			while (num != 1) {
				conditionA.await();
			}
			System.out.print(Thread.currentThread().getName() + r);
			System.out.print(" ");
			num = 2;
			conditionB.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}

	public void print3b(int r) {
		lock.lock();
		try {
			while (num != 2) {
				conditionB.await();
			}
			System.out.print(Thread.currentThread().getName() + r);
			System.out.print(" ");
			num = 1;
			conditionA.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}

public class Main {
	public static void main(String[] args) {
		ShareResource shareResource = new ShareResource();
		for (int i = 1; i < 4; i++) {
			int j = i;
			new Thread(() -> {
				shareResource.print3a(j);
			}, "A:").start();
			new Thread(() -> {
				shareResource.print3b(j);
			}, "B:").start();
		}
	}
}

你可能感兴趣的:(笔记)