传统线程同步通信技术

现有如下需求:

子线程10次与主线程100次,循环执行50次。

实现方法:

1、将子线程和主线程中要同步的方法进行封装,加上同步关键字实现同步;

2、两个线程间隔运行,添加一个标记变量进行比较以实现相互通信

具体代码如下:

package tradition;

/**
 * 传统线程间通信,wait和notify
 */
public class TraditionalThreadCommunication {

	/**
	 * 主方法
	 * @param args
	 */
	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 bShouldSub = true;
	
	/**
	 * 代表子线程的方法
	 * @param i
	 */
	public synchronized void sub(int i){
		//如果为false,则等待
		while(!bShouldSub) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		//如果bShouldSub为true则执行
		for(int j = 1; j <= 10; j ++){
			System.out.println("sub thread sequence of " 
					+ i +", loop of " + j);
		}
		//执行完之后将bShouldSub设置为false
		bShouldSub = false;
		this.notify();
	}
	
	/**
	 * 代表主线程的方法
	 * @param i
	 */
	public synchronized void main(int i){
		while(bShouldSub) {
			try {
				this.wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		for(int j = 1; j <= 100; j ++){
			System.out.println("main thread sequence of " + i 
					+", loop of " + j);
		}
		bShouldSub = true;
		this.notify();
	}
}
注意:wait()和notify()方法必须要在synchronized代码块中写。

参考视频:《Java多线程与并发库高级应用》


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值