java的wait与notify

      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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值