文档详情

Thread.ppt

发布:2016-09-24约字共41页下载文档
文本预览下载声明
在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
显示全部
相似文档