java线程技术6_线程的挂起和唤醒[转]
转自:http://blog.chinaunix.net/uid-122937-id-215913.html
1. 线程的挂起和唤醒
挂起实际上是让线程进入“非可执行”状态下,在这个状态下CPU不会分给线程时间片,进入这个状态可以用来暂停一个线程的运行;在线程挂起后,可以通过重新唤醒线程来使之恢复运行。
挂起的原因可能是如下几种情况:
(1)通过调用sleep()方法使线程进入休眠状态,线程在指定时间内不会运行。
(2)通过调用join()方法使线程挂起,使自己等待另一个线程的结果,直到另一个线程执行完毕为止。
(3)通过调用wait()方法使线程挂起,直到线程得到了notify()和notifyAll()消息,线程才会进入“可执行”状态。
(4)使用suspend挂起线程后,可以通过resume方法唤醒线程。
虽然suspend和resume可以很方便地使线程挂起和唤醒,但由于使用这两个方法可能会造成死锁,因此,这两个方法被标识为deprecated(抗议)标记,这表明在以后的jdk版本中这两个方法可能被删除,所以尽量不要使用这两个方法来操作线程。
调用sleep()、yield()、suspend()的时候并没有被释放锁
调用wait()的时候释放当前对象的锁
wait()方法表示,放弃当前对资源的占有权,一直等到有线程通知,才会运行后面的代码。
notify()方法表示,当前的线程已经放弃对资源的占有,通知等待的线程来获得对资源的占有权,但是只有一个线程能够从wait状态中恢复,然后继续运行wait()后面的语句。
notifyAll()方法表示,当前的线程已经放弃对资源的占有,通知所有的等待线程从wait()方法后的语句开始运行。
2.等待和锁实现资源竞争
等待机制与锁机制是密切关联的,对于需要竞争的资源,首先用synchronized确保这段代码只能一个线程执行,可以再设置一个标志位condition判断该资源是否准备好,如果没有,则该线程释放锁,自己进入等待状态,直到接收到notify,程序从wait处继续向下执行。
- synchronized(obj) {
- while(!condition) {
- obj.wait();
- }
- obj.doSomething();
- }
以上程序表示只有一个线程A获得了obj锁后,发现条件condition不满足,无法继续下一处理,于是线程A释放该锁,进入wait()。
在另一线程B中,如果B更改了某些条件,使得线程A的condition条件满足了,就可以唤醒线程A:
- synchronized(obj) {
- condition = true;
- obj.notify();
- }
需要注意的是:
# 调用obj的wait(), notify()方法前,必须获得obj锁,也就是必须写在synchronized(obj) {...} 代码段内。
# 调用obj.wait()后,线程A就释放了obj的锁,否则线程B无法获得obj锁,也就无法在synchronized(obj) {...} 代码段内唤醒A。
# 当obj.wait()方法返回后,线程A需要再次获得obj锁,才能继续执行。
# 如果A1,A2,A3都在obj.wait(),则B调用obj.notify()只能唤醒A1,A2,A3中的一个(具体哪一个由JVM决定)。
# obj.notifyAll()则能全部唤醒A1,A2,A3,但是要继续执行obj.wait()的下一条语句,必须获得obj锁,因此,A1,A2,A3只有一个有机会获得锁继续执行,例如A1,其余的需要等待A1释放obj锁之后才能继续执行。
# 当B调用obj.notify/notifyAll的时候,B正持有obj锁,因此,A1,A2,A3虽被唤醒,但是仍无法获得obj锁。直到B退出synchronized块,释放obj锁后,A1,A2,A3中的一个才有机会获得锁继续执行。
例1:单个线程对多个线程的唤醒
假设只有一个Game对象,但有3个人要玩,由于只有一个游戏资源,必须必然依次玩。
- /**
- * 玩游戏的人.
- * @version V1.0 ,2011-4-8
- * @author xiahui
- */
- public class Player implements Runnable {
- private final int id;
- private Game game;
- public Player(int id, Game game) {
- this.id = id;
- this.game = game;
- }
- public String toString() {
- return "Athlete<" + id + ">";
- }
- public int hashCode() {
- return new Integer(id).hashCode();
- }
- public void playGame() throws InterruptedException{
- System.out.println(this.toString() + " ready!");
- game.play(this);
- }
- public void run() {
- try {
- playGame();
- } catch (InterruptedException e) {
- System.out.println(this + " quit the game");
- }
- }
- }
游戏类,只实例化一个
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.Set;
- /**
- * 游戏类.
- * @version V1.0 ,2011-4-8
- * @author xiahui
- */
- public class Game implements Runnable {
- private boolean start = false;
- public void play(Player player) throws InterruptedException {
- synchronized (this) {
- while (!start)
- wait();
- if (start)
- System.out.println(player + " have played!");
- }
- }
- //通知所有玩家
- public synchronized void beginStart() {
- start = true;
- notifyAll();
- }
- public void run() {
- start = false;
- System.out.println("Ready......");
- System.out.println("Ready......");
- System.out.println("game start");
- beginStart();//通知所有玩家游戏准备好了
- }
- public static void main(String[] args) {
- Set<Player> players = new HashSet<Player>();
- //实例化一个游戏
- Game game = new Game();
- //实例化3个玩家
- for (int i = 0; i < 3; i++)
- players.add(new Player(i, game));
- //启动3个玩家
- Iterator<Player> iter = players.iterator();
- while (iter.hasNext())
- new Thread(iter.next()).start();
- Thread.sleep(100);
- //游戏启动
- new Thread(game).start();
- }
- }
程序先启动玩家,三个玩家竞争玩游戏,但只能有一个进入play,其他二个等待,进入的玩家发现游戏未准备好,所以wait,等游戏准备好后,依次玩。
运行结果
- Athlete<0> ready!
- Athlete<1> ready!
- Athlete<2> ready!
- Ready......
- Ready......
- game start
- Athlete<2> have played!
- Athlete<1> have played!
- Athlete<0> have played!
3.一次唤醒一个线程
一次唤醒所有玩家,但只有一个玩家能玩,不如一个一个唤醒
将上面的代码修改如下
- public void play(Player player) throws InterruptedException {
- synchronized (this) {
- while (!start)
- wait();
- if (start){
- System.out.println(player + " have played!");
- notify();//玩完后,通知下一个玩家来玩
- }
- }
- }
- //通知一个玩家
- public synchronized void beginStart() {
- start = true;
- notify();
- }
4.suspend挂起
该方法已不建议使用,例子如下
例2:suspend方法进行挂起和唤醒
- /**
- * suspend方法进行挂起和唤醒.
- * @version V1.0 ,2011-3-27
- * @author xiahui
- */
- public class SuspendThread implements Runnable{
- public void run() {
- try {
- Thread.sleep(10);
- } catch (Exception e) {
- System.out.println(e);
- }
- for (int i = 0; i <= 1; i ) {
- System.out.println(Thread.currentThread().getName() ":" i);
- }
- }
- public static void main(String args[]) throws Exception {
- Thread th1 = new Thread(new SuspendThread(),"thread1");
- Thread th2 = new Thread(new SuspendThread(),"thread2");
- System.out.println("Starting " th1.getName() "...");
- th1.start();
- System.out.println("Suspending " th1.getName() "...");
- //Suspend the thread.
- th1.suspend();
- th2.start();
- th2.join();
- // Resume the thread.
- th1.resume();
- }
- }
运行结果
- Starting thread1...
- Suspending thread1...
- thread2:0
- thread2:1
- thread1:0
- thread1:1
注意:
如果注释掉//th2.join();则thread2运行后,主线程会直接执行thread1的resume,运行结果可能会是
- Starting thread1...
- Suspending thread1...
- thread1:0
- thread1:1
- thread2:0
- thread2:1
参考文献
1.Java多线程设计模式:了解wait/notify机制. http://webservices.ctocio.com.cn/wsjavtec/335/8580335.shtml
2.Java中使用wait()与notify()实现线程间协作. http://www.bianceng.cn/Programming/Java/201103/25215.htm
java线程技术6_线程的挂起和唤醒[转]的更多相关文章
- Java后台技术(线程安全)
前端时间一个同事因为后台线程安全问题出了一次生产事故,今天我就对线程安全问题进行一次总结. 首先,我们来大致看以下我同事写的代码,代码我进行了精简,大致如下: for (final String re ...
- 【java并发】传统线程技术中创建线程的两种方式
传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...
- Java并发编程与技术内幕:线程池深入理解
摘要: 本文主要讲了Java当中的线程池的使用方法.注意事项及其实现源码实现原理,并辅以实例加以说明,对加深Java线程池的理解有很大的帮助. 首先,讲讲什么是线程池?照笔者的简单理解,其实就是一组线 ...
- Java面向对象 线程技术 -- 下篇
Java面向对象 线程技术 -- 下篇 知识概要: (1)线程间的通信 生产者 - 消费者 (2)生产者消费者案例优化 (3)守护线程 (4)停止线 ...
- Java多线程系列——过期的suspend()挂起、resume()继续执行线程
简述 这两个操作就好比播放器的暂停和恢复. 但这两个 API 是过期的,也就是不建议使用的. 不推荐使用 suspend() 去挂起线程的原因,是因为 suspend() 在导致线程暂停的同时,并不会 ...
- JAVA多线程提高一:传统线程技术&传统定时器Timer
前面我们已经对多线程的基础知识有了一定的了解,那么接下来我们将要对多线程进一步深入的学习:但在学习之前我们还是要对传统的技术进行一次回顾,本章我们回顾的则是:传统线程技术和传统的定时器实现. 一.传统 ...
- Java并发基础01. 传统线程技术中创建线程的两种方式
传统的线程技术中有两种创建线程的方式:一是继承Thread类,并重写run()方法:二是实现Runnable接口,覆盖接口中的run()方法,并把Runnable接口的实现扔给Thread.这两种方式 ...
- Java面向对象 线程技术--上篇
Java面向对象 线程 知识概要: (1)线程与进程 (2)自定义线程的语法结构 (3)多线程概念理解 (4)多线程状态图 (5)多线程--卖票 (6)同 ...
- 转:Java并发编程与技术内幕:线程池深入理解
版权声明:本文为博主林炳文Evankaka原创文章,转载请注明出处http://blog.csdn.net/evankaka 目录(?)[+] ); } catch (InterruptedExcep ...
随机推荐
- elastic search查询命令集合
Technorati 标签: elastic search,query,commands 基本查询:最简单的查询方式 query:{"term":{"title" ...
- 如何利用ZBrush中的DynaMesh创建身体(一)
之前的ZBrush教程中我们用Extract抽出功能演示了头发的立体雕刻方法,本讲将对已完成的头部模型添加躯干,使用DynaMesh创建身体的方法,以及人体比例和结构的介绍. 查看详细的视频教程可直接 ...
- Vector3D - AS3
Vector3D 类使用笛卡尔坐标 x.y 和 z 表示三维空间中的点或位置.与在二维空间中一样,x 属性表示水平轴,y 属性表示垂直轴.在三维空间中,z 属性表示深度.当对象向右移动时,x 属性的值 ...
- java 12-4 StringBuffer类的替换、反转、截取功能
1.StringBuffer的替换功能: public StringBuffer replace(int start,int end,String str):从start开始到end用str替换 pu ...
- 伪造Http头拿flag
<?php function GetIP(){ if(!empty($_SERVER["HTTP_CLIENT_IP"])) $cip = $_SERVER["HT ...
- 26Spring_的注解实际应用_关键整理一下之前的注解
写一个银行转账案例, 案例结构如下:
- easyui datagrid 多行删除问题
问题: var selected = $("#tbList").datagrid("getSelections"); selected的选中项 会包含上次已删掉 ...
- WebApi 消息拦截
最近公司要求对WebApi 实现服务端信息的监控(服务端信息拦截),由于本人之前没有做过这方便的相关项目所以在做的过程中也是困难重重,探索的过程也是非常痛苦的,好歹最终也算实现了这个功能.所以将这个分 ...
- mousewheel 模拟滚动
div{ box-sizing:border-box; } .father{ width:500px; height:400px; margin:auto; margin-top: 50px; bor ...
- HTTPS实现原理
HTTPS实现原理 HTTPS(全称:Hypertext Transfer Protocol over Secure Socket Layer),是以安全为目标的HTTP通道,简单讲是HTTP的安全版 ...