最简单了理解线程通信的举例

public class ThreadCommunicated {

	public static void main(String[] args) {
		final Printer p = new Printer();
		new Thread() {
			public void run() {
				while (true) {
					try {
						p.print1();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		// -----------------------------------------
		new Thread() {
			public void run() {
				while (true) {
					try {
						p.print2();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
}


//调用obj的wait(), notify()方法前,必须获得obj锁
//调用obj.wait()后,线程A就释放了obj的锁,否则线程B无法获得obj锁,、
//如果A1,A2,A3都在obj.wait(),则B调用obj.notify()只能唤醒A1,A2,A3中的一个(具体哪一个由JVM决定)。
class Printer {
	private  int flag = 1;

	public void print1() throws InterruptedException {
		//第0步:竞争锁,拿到锁的线程才能执行synchronized里面的语句块。没有拿到锁的线程在等待。
		synchronized (this) {
			//System.out.println("----print1---");
			if (flag == 1)                   // 第一步:    1 ==1  true     第七步:肯定拿到了锁
				this.wait();                //第二步  :      线程等待,不往下执行了,并释放锁
			System.out.print("天");
			System.out.print("津");
			System.out.print("滨");
			System.out.print("海");
			System.out.print("新");
			System.out.print("区\n");
			flag = 1;
			this.notifyAll();
		}
	}

	public void print2() throws InterruptedException {
		第0步:竞争锁,拿到锁的线程才能执行synchronized里面的语句块。没有拿到锁的线程在等待。
		synchronized (this) {        //第三步: 拿到了锁      ,继续执行。    
			if (flag == 2)           //第四步:   1 == 2 --> false,跳过等待。
				this.wait();
			System.out.print("北");
			System.out.print("京");
			System.out.print("颐");
			System.out.print("和");
			System.out.print("园\n");
			flag = 2;                
			this.notifyAll();          //第五步:唤醒刚才等待的全部线程
		}//退出synchronized块,释放锁,  第六步:   锁竞争.jvm随机分配给线程的锁,重复第0步
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值