——如果该方法调用的是不同的对象。 Object's wait() and notify or notifyAll() methods. The wait() method suspends the calling thread and temporarily releases ownership of the monitor (so it allows other threads to acquire the
monitor). The suspended thread that called wait() wakes up only when another thread calls notify() or notifyAll() on that object. wait 方法将挂起申请进入的线程并且暂时释放管程的所有权。(也就是说允许 了其他线程进入管程) 而挂起的线程只能在同一对象的其他线程中使用 notify 或 notifyAll 方法时才 能被唤醒。 The notifyAll() method wakes up all threads waiting on the object in question. The awakened threads compete for the monitor. One thread gets it, and the others go back to waiting. The notify() method arbitrarily wakes up one of the threads waiting on the object in question. comment: now it is not difficult to understand why the thread who calls wait(),notify(), notifyAll() should be monitor of the object :) notifyAll 方法的作用是唤醒关于同一对象其他所有的 waiting 的线程。而被唤 醒的线程互相竞争管程的所有权。其中的一个线程会取得所有权,然后其他的返 回 waiting 的队列继续等待。 notify 方法则是可以唤醒关于同一对象的任意某个线程。 注:现在应该不难理解为什么调用 wait、notify 或 notifyAll 方法的线程可能 进入管程了吧。 Each object has a queue that holds all threads waiting to execute one of the synchronized methods.There two ways for a thread to get onto this queue, either by calling the method while another thread is using the object or by calling wait(), while using the object. When a synchronized method call returns, or when a method calls wait(), another thread gets access to the object.If a thread was put in the queue by a call to wait(), it must be "unfrozen" by a call to notify() before it can be scheduled for execution again. 每个对象都有一个关于同
步方法的等待执行的线程队列。 线程要进入这个队列有 两种途径,可能是申请权限时已经被另一个线程占用而被放入等待队列的,也可 能是在它占用管程时,执行了 wait 方法而进入等待队列的。 当一个同步方法返回了值(执行完毕),或者执行了 wait,那么权限将被其他 的线程取得。如果一个线程已经被放入等待队列,那么它必须被以 notify 方法 “解冻”后才能被再次启用。
package xinhaoliang; public class xianshi { public static void main(String args[]) { //定义缓冲区 BufferLock buffer=new BufferLock(); //可以通过创建多个 Sender2 类的对象来实现创建多个生产者 //可以通过创建多个 Receiver2 类的对象来实现创建多个消费者 (new Receiver(buffer)).start(); (new Sender(buffer)).start(); (new Sender(buffer)).start(); (new Sender(buffer)).start(); (new Sender(buffer)).start(); (new Sender(buffer)).start(); (new Receiver(buffer)).start(); //通过设置 sleep 函数的参数实现主
程序的运行时间 try{ Thread.sleep(1000); }catch(InterruptedException e){} System.exit(0); } } //定义缓冲区,利用 Java 的同步机制可以实现管道机制,使线程只能互斥的访 问缓冲区 class BufferLock{ int bufferLangth=10; int []buffer =new int[bufferLangth]; int value; int Count,Rear,Front,i; public BufferLock(){ Count=0; Rear=0; Front=0; i=0; }
//消费元素的方法 void get()
{ while(Count==0){ try{ this.wait(); //Thread.sleep(10); }catch(InterruptedException e){} } value=buffer[Front]; Count--; Front=(Front+1)%bufferLangth; notifyAll(); } //生产元素的方法 void set(int value) { while(Count==buffe