- 1、本文档共50页,可阅读全部内容。
- 2、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
[工学]java多线程编程技术
作业 P337 1,2,3,4,5,6,7,8,9 对象锁的操作 Code or behavior Data or state Object this Thread before synchronized(this) Public void push(char c){ synchronized(this){ data[idx] = c ; idx++ ; } } Code or behavior Data or state Object this Thread after synchronized(this) Public void push(char c){ synchronized(this){ data[idx] = c ; idx++ ; } } 对象锁的操作 示例 将MyStack 对栈的push,pop操作都采用这种机制: public class MyStack{ … public void push( char c ){ synchronized(this){ data[idx] = c ; idx ++ ; } } public char pop( ){ synchronized(this){ idx-- ; return data[idx] ;} } } 线程 a 线程b 堆栈 s 状态 时刻t1 时刻t2 时刻t3 /*调 用s.push( ), 获得s的monitor后运行*/ data[idx]=‘r’ ; /*调用s.pop(),未获得s的monitor, b到s的lock pool中等待*/ //恢复运行 idx++ ; 。。。 /*完成,并交回S的 monitor*/ //线程a 被抢占 | p | q | r | | | | idx=2 | p | q | r | | | | idx=2 | p | q | r | | | | idx=3 . . . 多线程对共享数据进行操作 时刻t4 //运行pop … 得结果r | p | q | r | | | | idx=2 几点说明 如何返还对象的monitor 当synchronized( ){ }语句块执行完毕后。 当在synchronized( ){ }语句块中出现exception. 当调用该对象的wait( )方法。将该线程放入 对象的wait pool中,等待某事件的发生。 几点说明 ?对共享数据的所有访问都必须使用synchronized. ?用synchronized保护的共享数据必须是私有的,使线程 不能直接访问这些数据,必须通过对象的方法。 ?如果一个方法的整体都在synchronized块中,则可以把 synchronized关键字放于方法定义的头部: public synchronized void push( char c){ … } 几点说明 public class Reentrant { public synchronized void a() { b(); System.out.println(here I am, in a()); } public synchronized void b() { System.out.println(here I am, in b()); } } Java运行系统允许已经拥有某个对象锁的线程再次获得该对象的锁,这可以防止单个线程自己锁死自己。 避免死锁 ?死锁是指两个线程同时等待对方持有的锁。 ?死锁的避免完全由程序控制。 ?可以采用的方法: 如果要访问多个共享数据对象,则要从全局考虑定义 一个获得封锁的顺序,并在整个程序中都遵守这个 顺序。释放锁时,要按加锁的反序释放。 线程间的交互 ? Wait( ) 和notify( ) 线程在synchronized块中调用x.wait( )等待共享数据 的某种状态。该线程将放入对象x的wait pool, 并且将释 放x的monitor。 线程在改变共享数据的状态后,调用x.notify(),则对象 的wait pool中的一个线程将移入lock pool,等待x的monitor, 一旦获得便可以运行。 ? Notifyall( )把对象wait pool中的所有线程都移入lock pool。 * * 第13讲 线程 ?线程的概念 ?线程的创建 ?线程调度与线程控制 ?线程同步 ?线程状态与生命周期 学习任务:了解并掌握JAVA多线程程序设计的方法
文档评论(0)