1. 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
  2. 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  3. 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Thread

在Java 语言中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。 每个对象都对应于一个可称为“互斥锁”的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。 关键字synchronized 来与对象的互斥锁联系。当某个对象用synchronized修饰时,表明该对象在任一时刻只能由一个线程访问。 public void push(char c){ synchronized(this){ data[idx]=c; idx++; } } public char pop(){ synchronized(this){ idx--; return data[idx]; } } synchronized 除了象上面讲的放在对象前面限制一段代码的执行外,还可以放在方法声明中,表示整个方法为同步方法。 public synchronized void push(char c){ … } 如果synchronized用在类声明中,则表明该类中的所有方法都是synchronized的。 多线程的通信 class SyncStack{ private int index = 0; private char []buffer = new char[6]; public synchronized void push(char c){ while(index == buffer.length){ try{ this.wait(); }catch(InterruptedException e){} } this.notify(); buffer[index] = c; index++; } public synchronized char pop(){ while(index ==0){ try{ this.wait(); }catch(InterruptedException e){} } this.notify(); index--; return buffer[index]; } } 生产者-消费者问题 class Producer implements Runnable{ SyncStack theStack; public Producer(SyncStack s){ theStack = s; } public void run(){ char c; for(int i=0; i20; i++){ c =(char)(Math.random()*26+A); theStack.push(c); System.out.println(Produced: +c); try{ Thread.sleep((int)(Math.random()*100)); }catch(InterruptedException e){} } } } class Consumer implements Runnable{ SyncStack theStack; public Consumer(SyncStack s){ theStack = s; } public void run(){ char c; for(int i=0;i20;i++){ c = theStack.pop(); System.out.println(Consumed: +c); try{ Thread.sleep((int)(Math.random()*1000)); }catch(InterruptedException e){} } } } public class SyncTest{ public static void main(String args[]){ SyncStack stack = new SyncStack(); Runnable source=new Producer(stack); Runnable sink = new Consumer(stack); Thread t1 = new Thread(source); Thread t2 = new Thread

文档评论(0)

wf93679 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档