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();}}
阅读全文
0 0
- java多线程通信
- Java多线程通信机制
- Java多线程通信机制
- Java多线程通信机制
- java 多线程通信
- java多线程通信方法
- java多线程通信方法
- java--多线程通信
- JAVA多线程通信
- java多线程线程通信
- Java多线程通信
- Java多线程通信机制
- Java多线程通信
- java多线程通信方法
- Java - 多线程通信
- Java多线程通信方式
- Java 多线程通信
- Java 多线程:线程通信
- Link Cut Tree学习小记
- 高精度减法
- 01_入门指南--01_构建程序
- 排序(2)快速排序
- 2. Android
- java------多线程通信
- HTML--列表标签应用
- Java多线程学习总结(一)——多线程创建
- [Unity] Unity渲染优化
- window下C语言实现读取config.ini配置文件
- struts2:This method: login for action user is not allowed!
- 关于事件分发机制的思考
- 关于Boost
- Android性能优化之利用LeakCanary检测内存泄漏及解决办法