JAVA多线程通信
JAVA多线程通信
package com.frank.thread;/** * author:pengyan * date:Jun 16, 2011 * file:ProducerAndCustomerTest.java */ public class ProducerAndCustomerTest {public static void main(String[] args) {//create an object Queue q=new Queue();Productor p=new Productor(q);Customer c=new Customer(q);//p and c shared qp.start();c.start();}}class Customer extends Thread{Queue q;public Customer(Queue q) {this.q=q;}@Overridepublic void run() {while (q.value<10) {//get the valueSystem.out.println("Customer get "+q.get());}}}class Productor extends Thread{Queue q;public Productor(Queue q) {this.q=q;}@Overridepublic void run() {for (int i = 1; i <=10; i++) {q.put(i);//product and show infoSystem.out.println("Productor put "+i);}}}class Queue{int value;//count the mumberboolean bFull=false;//whether the cup is fullpublic synchronized void put(int i){if (!bFull) {value=i;//fill the cup bFull=true;//it is fullnotifyAll();//notify other threadtry {wait();//wait.......} catch (InterruptedException e) {e.printStackTrace();}}}public synchronized int get(){if (!bFull) {try {wait();//if not full,wait until full} catch (InterruptedException e) {e.printStackTrace();}}bFull=false;//after got the cup is emptynotifyAll();//notify the Productor to putreturn value;//return the value}}?
控制台打印:
Productor put 1
Customer get 1
Customer get 2
Productor put 2
Customer get 3
Productor put 3
Customer get 4
Productor put 4
Customer get 5
Productor put 5
Productor put 6
Customer get 6
Productor put 7
Customer get 7
Customer get 8
Productor put 8
Customer get 9
Productor put 9
Customer get 10
Productor put 10