关于线程同步的实践的例子

package cn.itcast.demo;
/*
 * 有两个线程,一个子线程,一个主线程,主线程先运行十次,然后子线程运行100次,如此循环进行五十次
 * 
 * 
 * 
 */
public class TraditionalThreadCommunicationDemo {
	
	public static void main(String[] args) {
		final Bussiness bussiness = new Bussiness();
		new Thread(new Runnable(){
			
			public void run() {
				for (int i = 0; i < 50; i++) {
					bussiness.sub();
				}
			}
		}).start();
		
		for (int j = 0; j < 50; j++) {
			bussiness.main();
		}
	}

}

class  Bussiness{
	private boolean flag = true;
	/*
	 * 
	 * 这个例子同步锁定的对象是这个类本身,即this
	 */
	public synchronized void main()
	{
		while/*if*/(flag)
		{
			for (int i = 0; i < 10; i++) {
				System.out.println("this is main of " + i);
			}
			flag = false;
			//唤起在此对象监视器的那个对象
			this.notify();
		}
		try {
			//让当前的等待,知道其他对象调用此对象的notify方法或notifyAll()方法
			this.wait();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public synchronized  void sub()
	{
		/*
		 * 有时候一种叫做伪唤醒的情况,这时候如果用if就不会再判断了,就会往下运行,这时候就可能会出错
		 * 但是如果用while就算是出现伪唤醒还是会去判断就不会出错。这里用while体现了你的水平
		 */
		while/*if*/(!flag)
		{
			for (int i = 0; i < 100; i++) {
				System.out.println("this is sub of " + i);
			}
			flag = true;
			this.notify();
		}
		try {
			this.wait();//这里等待,知道被唤醒,被唤醒的时候其实就是回到了这行代码这里
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值