java 线程同步 notify wait

本文详细介绍了如何在一个程序中实现子线程与主线程的交替循环操作,通过实例展示了同步机制的运用,以及如何在并发环境中确保数据的一致性和正确执行流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次。摘自张孝祥老师线程视频源码

package test;

public class Test {
	// 子线程循环10次,主线程循环100次。接着子线程循环10次,主线程循环100次。如此循环50次
	public static void main(String[] args) {
		new Test().init();

	}

	private void init() {
		final Business business = new Business();
		new Thread() {
			public void run() {
				for (int i = 1; i <= 10; i++) {
					business.subdo();// 子线程
				}
			};
		}.start();
		for (int i = 1; i <= 10; i++) {
		//	business.subdo();// 子线程
			business.maindo();
		}

	}

	class Business {
		private boolean isShouldSub = true;

		public void subdo() {
			synchronized (Test.class) {
				if (!isShouldSub) {// 如果不该子线程执行
					try {
						Test.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				for (int i = 1; i <= 10; i++) {
					System.out.println(Thread.currentThread().getName()
							+ " running .." + "  " + i + "次");
				}
				isShouldSub=false;
				Test.class.notifyAll();
			}

		}

		public void maindo() {
			synchronized (Test.class) {
				if (isShouldSub) {
					try {
						Test.class.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				for (int i = 1; i <= 20; i++) {
					System.out.println(Thread.currentThread().getName()
							+ " running .." + "  " + i + "次");
				}
				isShouldSub=true;
				Test.class.notifyAll();
			}
		}
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值