java------多线程通信
生活随笔
收集整理的這篇文章主要介紹了
java------多线程通信
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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++; //存完位置加1if (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();}}
總結
以上是生活随笔為你收集整理的java------多线程通信的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JEECG参与2017年度最受欢迎开源项
- 下一篇: 微信、企业微信和支付窗 SDK 三合一,