java多线程间的通讯
生活随笔
收集整理的這篇文章主要介紹了
java多线程间的通讯
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
什么是多線程之間的通訊? 就是多個線程在操作同一個資源,但是操作的動作不同。
??
?
package com;class Printer{// 打印機public String fileName;public String fileType;// true: 生產者正在生產數據,消費者應該進入休眠狀態// false:消費者正在消費數據,生產者應該進入休眠狀態boolean flag = true; }// wait和notify方法要在線程同步中使用 // wait,notify, notifyAll方法都是Object里的方法,用來控制線程的狀態// wait: 讓持有該對象的線程把該對象的控制權交出去,然后處于等待狀態。 // notify: 通知某個正在等待這個對象的控制權的線程可以繼續運行。class Out extends Thread{Printer print;public Out(Printer print){this.print = print;}@Overridepublic void run() {int count = 0;while(true){synchronized (print) {System.out.println("生產者:"+print.flag);if(!print.flag){try {print.wait(); // 消費者正在消費,生產者應該休眠// 當執行完wait方法后,該線程就進入休眠,下面的代碼就不會被執行} catch (InterruptedException e) {e.printStackTrace();}}//System.out.println("生產者:"+print.flag);if(count == 0){print.fileName = "三國演義";print.fileType = "pdf";}else{print.fileName = "紅樓夢";print.fileType = "txt";}count = (count + 1)%2;print.flag = false;//System.out.println("生產者生產完畢");print.notify();}}} }class Input extends Thread{Printer print;public Input(Printer print){this.print = print;}@Overridepublic void run() {while(true){synchronized (print) {//System.out.println("消費者:"+print.flag);if(print.flag){try {print.wait(); // 生產者正在生產,消費者應該休眠} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}System.out.println(print.fileName+", "+print.fileType);print.flag = true;print.notify(); // 消費消費完畢, 喚醒生產者//System.out.println("消費者消費完畢");}}} }public class OutInputThread extends Thread{public static void main(String[] args){Printer print = new Printer();Out out = new Out(print);Input input = new Input(print);out.start();input.start();} }?
wait和sleep的區別:?
? wait可以釋放鎖的資源,而sleep不會釋放資源
? wait需要notify才能從休眠狀態變為運行狀態。sleep時間到期,會自動從休眠狀態到運行狀態。
總結
以上是生活随笔為你收集整理的java多线程间的通讯的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 汇编:ZF(zero flag)标志位
- 下一篇: 汇编:PF标志位