线程的互斥与同步通信

synchronized的使用和wait与notify实现线程间的通信

案例: 子线程循环10次, 主线程循环5次, 两者交替运行50次

代码
package thread;

public class TraditionalThreadCommunication {
	public static void main(String[] args) {

		final Bussiness bussiness = new Bussiness();

		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					bussiness.sub(i);
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			bussiness.main(i);
		}
	}
}

class Bussiness {
	private boolean flag = true;

	public synchronized void sub(int j) {
		// 如果flag为false则等待
		while (!flag) {// 使用while 比较好 可以防止假唤醒
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 10; i++) {
			System.out.println("sub : " + i + " 第" + j + "次外循环");
		}
		// 将flag置为false 并唤醒主线程
		flag = false;
		this.notify();
	}

	public synchronized void main(int j) {
		// 如果flag为true则等待
		while (flag) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int i = 1; i <= 5; i++) {
			System.out.println("main : " + i + " 第" + j + "次外循环");
		}
		// 将flag置为true 并唤醒子线程
		flag = true;
		this.notify();
	}
}

将需要互斥的资源(属性和方法) 统一定义在一个类中, 而不是将互斥代码写到线程中, 这样做的好处是以后任何线程再访问资源类的时候就可以保证是线程安全的

注意: 使用notify()和notifyAll()方法的时候是不会释放锁资源的


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值