关于Object类中的wait和notify方法(生产者和消费者模式)
1.wait和notify方法不是线程对象的方法,是java中任何一个java对象都有的方法,因为这两个方法都是Object类中自带的。
wait方法和notify方法不是通过线程对象调用,如:t.wait() t.notify().
2.wait()方法作用
Object o=new Object();
o.wait();
表示:让正在o对象上活动的线程进入等待状态,无期限等待,直到被唤醒为止
3.notify()方法作用
作用:唤醒正在o对象上等待的线程。
还有一个notifyAll()方法,这个方法就是唤醒o对象上处于等待的所有线程。
4.生产者和消费者模式
为了专门解决某个特定需求的。

1 package XianChengFenXi; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 /* 7 * 使用wait方法和notify方法实现生产者和消费者模式:生产线程和消费线程达到均衡。 8 * 需要使用wait方法和notify方法 9 * wait方法和notify方法都是建立在线程同步的基础上。 10 */ 11 12 public class ThreadTest17 { 13 public static void main(String[] args){ 14 List list=new ArrayList(); 15 16 //创建两个线程:生产者线程和消费者线程 17 Thread t1=new Thread(new Producer(list)); 18 Thread t2=new Thread(new Consumer(list)); 19 20 t1.setName("生产者线程"); 21 t2.setName("消费者线程"); 22 23 t1.start(); 24 t2.start(); 25 26 27 } 28 29 } 30 //生产线程 31 class Producer implements Runnable{ 32 33 private List list;//用List模拟一个仓库 34 public Producer(List list){ 35 this.list=list; 36 } 37 public void run(){ 38 //一直生产 39 synchronized(list){ //给仓库对象list加锁 40 while(true){ 41 if(list.size()>1){ 42 try { 43 list.wait();//停止生产,即让当前线程进入等待状态,并且释放list集合的锁 44 45 } catch (InterruptedException e) { 46 // TODO Auto-generated catch block 47 e.printStackTrace(); 48 } 49 } 50 Object obj=new Object(); 51 list.add(obj); 52 System.out.println(Thread.currentThread().getName()+"----->"+obj); 53 54 //唤醒消费者进行消费 55 list.notify(); 56 } 57 } 58 } 59 } 60 //消费线程 61 class Consumer implements Runnable{ 62 private List list;//用List模拟一个仓库 63 public Consumer(List list){ 64 this.list=list; 65 } 66 public void run(){ 67 //一直消费 68 synchronized(list){ //给仓库对象list加锁 69 while(true){ 70 if(list.size()==0){ 71 try { 72 list.wait();//停止消费,即让当前线程进入等待状态,并且释放list集合的锁 73 } catch (InterruptedException e) { 74 // TODO Auto-generated catch block 75 e.printStackTrace(); 76 } 77 } 78 Object obj=list.remove(0); 79 System.out.println(Thread.currentThread().getName()+"----->"+obj); 80 //唤醒生产者进行生产 81 list.notify(); 82 } 83 } 84 } 85 }

浙公网安备 33010602011771号