当前位置:首页 > 开发 > 编程语言 > 消息中间件 > 正文

java的wait与notify

发表于: 2013-03-26   作者:bijian1013   来源:转载   浏览次数:
摘要:       wait与notify是java同步机制中重要的组成部分。结合与synchronized关键字使用,可以建立很多优秀的同步模型。       synchronized(this){}等价与public synchronized void method(){.....}    

      wait与notify是java同步机制中重要的组成部分。结合与synchronized关键字使用,可以建立很多优秀的同步模型。

      synchronized(this){}等价与public synchronized void method(){.....}

      同步分为类级别和对象级别,分别对应着类锁和对象锁。类锁是每个类只有一个,如果static的方法被synchronized关键字修饰,则在这个方法被执行前必须获得类锁;对象锁与类锁类似。

      首先,调用一个Object的wait与notify/notifyAll的时候,必须保证调用代码对该Object是同步的,也就是说必须在作用等同于synchronized(obj){......}的内部才能够去调用obj的wait与notify/notifyAll三个方法,否则就会报错:

      java.lang.IllegalMonitorStateException: current thread not owner

      在调用wait的时候,线程自动释放其占有的对象锁,同时不会去申请对象锁。当线程被唤醒的时候,它才再次获得了去获得对象锁的权利。

      所以,notify与notifyAll没有太多的区别,只是notify仅唤醒一个线程并允许它去获得锁,notifyAll是唤醒所有等待这个对象的线程并允许它们去获得对象锁,只要是在synchronied块中的代码,没有对象锁是寸步难行的。其实唤醒一个线程就是重新允许这个线程去获得对象锁并向下运行。

       顺便说一下notifyall,虽然是对每个wait的对象都调用一次notify,但是这个还是有顺序的,每个对象都保存这一个等待对象链,调用的顺序就是这个链的顺序。其实启动等待对象链中各个线程的也是一个线程,在具体应用的时候,需要注意一下。

      网上找的一个实例:

package com.bijian.thread;

public class ThreadAttemper {
	
	public static void main(String[] args) {
		ThreadA a = new ThreadA();
		a.start();
		System.out.println("a is start....");
		synchronized (a) {
			try {
				System.out.println("Waiting for a to complete...");
				a.wait();
				System.out.println("a completed.Now back to main thread");
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Total is :" + a.total);
	}
}

class ThreadA extends Thread {
	int total;
	public void run() {
		synchronized (this) {
			System.out.println("ThreadA is running..");
			for (int i = 0; i < 5; i++) {
				total += i;
				System.out.println("total is " + total);
			}
			notify();
		}
	}
}

       运行结果:

a is start....
ThreadA is running..
total is 0
total is 1
total is 3
total is 6
total is 10
Waiting for a to complete...

         发现程序在一直在a.wait();处,分析不难发现:ThreadA线程已运行结束,对于线程运行结束的对象,因其不可能再执行notify();从而激活主线程中的wait()方法,故一直停在这,不能往下执行。

      修改方法有两个:

      1.法一(不推荐):在ThreadA类的run方法中增加sleep方法,使主方法运行至a.wait();处时,ThreadA类的线程还未运行结束。如下所示:

package com.bijian.thread;

public class ThreadAttemper {
	
	public static void main(String[] args) {
		ThreadA a = new ThreadA();
		a.start();
		System.out.println("a is start....");
		synchronized (a) {
			try {
				System.out.println("Waiting for a to complete...");
				a.wait();
				System.out.println("a completed.Now back to main thread");
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Total is :" + a.total);
	}
}

class ThreadA extends Thread {
	int total;
	public void run() {
		synchronized (this) {
			System.out.println("ThreadA is running..");
			for (int i = 0; i < 5; i++) {
				try {
					this.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				total += i;
				System.out.println("total is " + total);
			}
			notify();
		}
	}
}

       运行结果:

a is start....
Waiting for a to complete...
ThreadA is running..
total is 0
total is 1
total is 3
total is 6
total is 10
a completed.Now back to main thread
Total is :10

 

      2.法二(推荐):在main方法的a.wait()方法前增加判断,判断ThreadAA类的线程是否处于活动状态。如下所示:

package com.bijian.thread;

public class ThreadAttemper {
	
	public static void main(String[] args) {
		ThreadA a = new ThreadA();
		a.start();
		System.out.println("a is start....");
		synchronized (a) {
			try {
				System.out.println("Waiting for a to complete...");
				//测试线程是否处于活动状态
				if(a.isAlive()) {
					a.wait();
				}
				System.out.println("a completed.Now back to main thread");
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Total is :" + a.total);
	}
}

class ThreadA extends Thread {
	int total;
	public void run() {
		synchronized (this) {
			System.out.println("ThreadA is running..");
			for (int i = 0; i < 5; i++) {
				total += i;
				System.out.println("total is " + total);
			}
			notify();
		}
	}
}

       运行结果:

a is start....
Waiting for a to complete...
ThreadA is running..
total is 0
total is 1
total is 3
total is 6
total is 10
a completed.Now back to main thread
Total is :10

 

 

        从上面的实例我们不难看到:“main()方法在子线程未执行结束时不会结束”。据此思想,我们可以扩展此实例,解决一些现实问题。如main方法启动多个线程依次做一些事情。

      扩展实例如下:

package com.bijian.thread;

public class ThreadAttemperA {
	
	public static void main(String[] args) {
		
		ThreadA a = new ThreadA();
		a.start();//启动a线程
		System.out.println("a is start....");
		synchronized (a) {
			try {
				System.out.println("Waiting for a to complete...");
				if(a.isAlive()) {
					a.wait();
				}
				System.out.println("a completed.Now back to main thread");
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Total is :" + a.total);
		
		ThreadB b = new ThreadB();
		b.start();//启动b线程
		System.out.println("b is start....");
		synchronized (b) {
			try {
				System.out.println("Waiting for b to complete...");
				if(b.isAlive()) {
					b.wait();
				}
				System.out.println("b completed.Now back to main thread");
			} catch (InterruptedException e) {
			}
		}
		System.out.println("Total is :" + b.total);
	}
}

class ThreadA extends Thread {
	int total;
	public void run() {
		synchronized (this) {
			System.out.println("ThreadA is running..");
			for (int i = 0; i < 5; i++) {
				total += i;
				System.out.println("total is " + total);
			}
			notify();
		}
	}
}

class ThreadB extends Thread {
	int total;
	public void run() {
		synchronized (this) {
			System.out.println("ThreadB is running..");
			for (int i = 0; i < 10; i++) {
				total += i;
				System.out.println("total is " + total);
			}
			notify();
		}
	}
}

     运行结果:

a is start....
Waiting for a to complete...
ThreadA is running..
total is 0
total is 1
total is 3
total is 6
total is 10
a completed.Now back to main thread
Total is :10
b is start....
Waiting for b to complete...
ThreadB is running..
total is 0
total is 1
total is 3
total is 6
total is 10
total is 15
total is 21
total is 28
total is 36
total is 45
b completed.Now back to main thread
Total is :45

       从运行结果来看,虽有多个线程,但必须是第一个线程执行完成,再执行下一个线程,即是串行的。在串行的业务场景下,可以用此方法。

java的wait与notify

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

编辑推荐
继续来看blog:http://blog.csdn.net/zyplus/article/details/6672775 “Obj.wait(),与Obj.notify(
Java 中除了关键字 synchronized 能够实现线程同步外,还可以使用 wait 和 notify/notify 实现同步
线程同步 前言:我们上一篇http://davidisok.iteye.com/blog/2105369讲了线程的基本介绍,这一篇主
wait-notify机制 a. 当synchronized方法中的wait方法被调用时,当前线程将被中断运行,并且放弃该对
注意:这些方法属于Object,而不属于Thread。 每一个对象除了有一个锁之外,还有一个等待队列(wait
wait-notify机制 a. 当synchronized方法中的wait方法被调用时,当前线程将被中断运行,并且放弃该对
1、问题的引出 class MyThread implements Runnable{ private int ticket = 5 ; // 假设一共有5张票
wait, notify 和 notifyAll,这些在多线程中被经常用到的保留关键字,在实际开发的时候很多时候却并
wait-notify用在经典的生产者-消费者模型。一般代码都是先初始化consumer,然后再初始化producer,
wait-notify用在经典的生产者-消费者模型。一般代码都是先初始化consumer,然后再初始化producer,
版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号