java的wait与notify

news/2024/5/17 20:21:46 标签: java, thread, wait, notify, synchronized

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

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

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

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

      java.lang.IllegalMonitorStateException: current thread not owner

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

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

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

      网上找的一个实例:

java">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类的线程还未运行结束。如下所示:

java">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类的线程是否处于活动状态。如下所示:

java">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方法启动多个线程依次做一些事情。

      扩展实例如下:

java">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

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


http://www.niftyadmin.cn/n/1319131.html

相关文章

spring.net之aop加单例模式编写无try catch程序

为应付软件小白的各种无脑操作&#xff08;不过话说回来&#xff0c;软件就是给小白使用的&#xff09;&#xff0c;常常需要在调用方法时增加众多重复的try/catch&#xff0c;后来拜读artech的《如何编写没有Try/Catch的程序》&#xff0c;了解到可以将try/catch统一处理&…

守护线程概念及实例

守护线程在没有用户线程可服务时自动离开&#xff0c;在Java中比较特殊的线程是被称为守护&#xff08;Daemon&#xff09;线程的低级别线程。这个线程具有最低的优先级&#xff0c;用于为系统中的其它对象和线程提供服务。 将一个用户线程设置为守护线程的方式是在线程对象创建…

Android学习链接大放送

虽然贴链接这种事情。。真是一种很偷懒的做法。。。 但是我一个小菜鸟&#xff0c;果断还是要以多向别人学习为主。。。 好资源要和大家分享对不对&#xff01; 况且。。放博客里。。比收藏夹的利用几率要大一点&#xff01; 原作者应该也很喜欢我这种贴链接打广告的做法吧。。…

java.sql.SQLException: ORA-01461: can bfor insert into a LONG column问题分析与小结

java.sql.SQLException: ORA-01461: can bfor insert into a LONG column 1.发现系统报此问题的第一反应是插入数据时&#xff0c;数据长度超出数据库的字段长度。 2.而根据错误日志不难分析出是向邮件发送信息表中插入数据时&#xff0c;数据超过定义的最大值限制了&#xff0…

python tips - 静态方法和类成员方法

摘自 《Python 基础教程》 9.5.2 静态方法和类成员方法 p149 在讨论实现属性的旧方法前&#xff0c;先让我们绕道而行&#xff0c;看看另一对实现方法和新式属性的实现方法类似的特征。静态方法和类成员方法分别在创建时被装入Staticmethod类型和Classmethod类型的对象中。…

JSP中文乱码分析

在JSP的开发过程中&#xff0c;经常出现中文乱码的问题。 首先了解一下Java中文问题的由来&#xff1a; Java的内核和class文件是基于unicode的&#xff0c;这使Java程序具有良好的跨平台性&#xff0c;但也带来了一些中文乱码问题的麻烦。原因主要有两方面&#xff0c;Java和J…

java多线程join的作用与用法

对于JAVA的join&#xff0c;JDK 是这样说的&#xff1a;join public final void join &#xff08;long millis &#xff09;throws InterruptedException Waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever。字面意思是等待一…

请修改这段程序,立刻!

你们正在开发一个新项目&#xff0c;你在一个地方看到一段有问题的代码。错误的处理方式是&#xff0c;“啊&#xff0c;别人写的&#xff0c;我最好别碰它”&#xff0c;“我没有时间去改它——我有自己的事要做”&#xff0c;“如果我修改它&#xff0c;肯定会改出问题”。问…