欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java通过wait()和notifyAll()方法实现线程间通信

程序员文章站 2024-03-02 18:22:58
本文实例为大家分享了java实现线程间通信的具体代码,供大家参考,具体内容如下 java代码(使用了2个内部类): package threads; im...

本文实例为大家分享了java实现线程间通信的具体代码,供大家参考,具体内容如下

java代码(使用了2个内部类):

package threads;

import java.util.linkedlist;

/**
 * created by frank
 */
public class prodcons {
 protected linkedlist<object> list = new linkedlist<>();
 protected int max;
 protected boolean done = false;

 public static void main(string[] args) throws interruptedexception {
  prodcons prodcons = new prodcons(100, 3, 4);
  thread.sleep(5 * 1000);
  synchronized (prodcons.list) {
   prodcons.done = true;
   try {
    prodcons.notifyall();
   } catch (exception ex) {
   }
  }
 }

 private prodcons(int maxthreads, int np, int nc) {
  this.max = maxthreads;
  for (int i = 0; i < np; i++) {
   new producer().start();
  }
  for (int i = 0; i < nc; i++) {
   new consumer().start();
  }
 }

 class producer extends thread {
  public void run() {
   while (true) {
    object justproduced = null;
    try {
     justproduced = getobj();
    } catch (interruptedexception e) {
     e.printstacktrace();
    }
    synchronized (list) {
     while (list.size() == max) {
      try {
       list.wait();
      } catch (interruptedexception e) {
       system.out.println("producer interrupted");
      }
     }
     list.addfirst(justproduced);
     list.notifyall();
     system.out.println("produced 1;list size now " + list.size());
     if (done) {
      break;
     }
    }
   }
  }
 }

 class consumer extends thread {
  public void run() {
   while (true) {
    object object = null;
    synchronized (list) {
     if (list.size() == 0) {
      try {
       list.wait();
      } catch (interruptedexception e) {
       system.out.println("consumer interrupted");
      }
     }
     if (list.size() > 0) {
      object = list.removelast();
     }
     list.notifyall();
     system.out.println("list size now " + list.size());
     if (done) {
      break;
     }
    }
    if (null != object) {
     system.out.println("consuming object " + object);
    }
   }
  }
 }

 private object getobj() throws interruptedexception {
  thread.sleep(1000);
  return new object();
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。