java------多线程通信

来源:互联网 发布:淘宝上的nba旗舰店 编辑:程序博客网 时间:2024/06/11 14:11
package xc;class Storage{//数据存储数组private int [] cells=new int [10];//inPos表示存入时数组下标,outPos表示取出数组下标private int inPos;private int outPos;private int count;//定义一个put方法向数组中存入数据public synchronized void put(int num){try {while (count==cells.length) {this.wait();}cells[inPos]=num;    System.out.println("在cells["+inPos+"]中放入---"+cells[inPos]);    inPos++;           //存完位置加1     if (inPos==cells.length) inPos=0; //当inpos为数组长度时将其置为0;count++;this.notify();     } catch (Exception e) {e.printStackTrace();}}//定义一个get方法方法取出数据public  synchronized void get(){try {while (count==0) {this.wait();}int data=cells[outPos];     System.out.println("从celss["+outPos+"]中取出的数据"+data);     outPos++;  if (outPos==cells.length) {outPos=0;  }count--;this.notify();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}package xc;public class InPut implements Runnable {private Storage st;private int num;public InPut(Storage st) {//通过构造方法接受一个Storage对象this.st=st;}public void run(){while (true) {st.put(num++);//将num存入数组,没次存入后num值自增}}}package xc;class  OutPut implements Runnable{   //输出线程类private Storage st;public OutPut(Storage st) {//通过构造方法接受一个Storage对象this.st=st;}public void run(){while (true) {st.get();//取出元素}}}package xc;public class Example18 {public static void main(String[] args) {// TODO Auto-generated method stubStorage st=new Storage();InPut inPut=new InPut(st);    OutPut outPut=new OutPut(st);    new Thread(inPut).start();    new Thread(outPut).start();}}