当前位置: 移动技术网 > IT编程>开发语言>Java > Java通过wait()和notifyAll()方法实现线程间通信

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了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();
 }
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网