两个线程A和B, A打印1, 3, ..., 99, B打印2, 4, ..., 100, 要求A和B严格交替打印(Java实现)

第一种实现:

public class ThreadAB1 {
	Thread A = new Thread(new Runnable() {
		public void run() {
			for (int i = 1; i < 100; i += 2) {
				print("A " + i);
			}
		}
	});
	Thread B = new Thread(new Runnable() {
		public void run() {
			for (int i = 2; i <= 100; i += 2) {
				print("B " + i);
			}
		}
	});

	private synchronized void print(String str) {
		notify();
		System.out.println(str);
		try {
			wait();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		ThreadAB1 instance = new ThreadAB1();
		instance.A.start();
		instance.B.start();
	}
}

第二种实现:

public class ThreadAB2 {
	private static Object LOCK = new Object();
	private static boolean flag = false;

	public static void main(String[] args) {
		Thread A = new Thread() {
			public void run() {
				for (int i = 1; i < 100; i += 2) {
					synchronized (LOCK) {
						System.out.println("A " + i);
						if (!flag) {
							flag = true;
							LOCK.notify();// 在这里虽然唤醒了另一个线程b,但锁并没有释放
							if (i < 100) {
								try {
									LOCK.wait();// 在wait后的瞬间线程b得到锁
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						}
					}
				}
			}
		};

		Thread B = new Thread() {
			public void run() {
				for (int i = 2; i <= 100; i += 2) {
					synchronized (LOCK) {
						System.out.println("B " + i);
						if (flag) {
							flag = false;
							LOCK.notify();
							if (i < 100) {
								try {
									LOCK.wait();
								} catch (InterruptedException e) {
									e.printStackTrace();
								}
							}
						}
					}
				}
			}
		};

		A.start();
		B.start();
	}
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值