传统线程同步通信技术(三)

一. 线程通信:

在同步方法中,线程之间的通信主要依靠以下三个方法来实现:

1. wait() 调用该方法会使当前线程暂停执行并释放对象锁,让其他线程可以进入Synchronized代码块,当前线程放入对象等待池中。

2. notify() 调用该方法会从对象等待池中移走任意一个线程

3. notifyAll() 调用该方法会从对象等待池中移走所有等待的线程。


二. 一道面试题:

子线程循环10次,接着主线程循环100次, 接着又回到子线程循环10次,接着再回到主线程循环100次,如此循环50次,代码如下:

public class TraditionalThreadCommunication {
	public static void main(String[] args) {
		final Business business = new Business();
		new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 1; i <= 50; i++) {
					business.sub(i); // 调用子线程
				}
			}
		}).start();

		for (int i = 1; i <= 50; i++) {
			business.main(i); // 调用主线程
		}
	}
}

class Business {
	private boolean shouldSubRun = true;   

	public synchronized void sub(int i) {
		while (!shouldSubRun) {
			try {
				// 没轮到自己就等一会
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j <= 10; j++) {
			System.out.println("sub thread sequence of  " + j + " , loop of  " + i);
		}
		shouldSubRun = false;
		// 唤醒下一个等待的线程
		this.notify();
	}

	public synchronized void main(int i) {
		while (shouldSubRun) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		for (int j = 1; j <= 100; j++) {
			System.out.println("main thread sequence of  " + j + " , loop of  " + i);
		}
		shouldSubRun = true;
		this.notify();
	}
}
注意点:

1. 使用while循环可以防止线程自己唤醒自己,即“伪唤醒”。

2. 要用的公共数据的若干方法写在一个类中,这种设计体现了高类聚和程序的健壮性。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值