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 q
p.start();
c.start();
}
}
class Customer extends Thread{
Queue q;
public Customer(Queue q) {
this.q=q;
}
@Override
public void run() {
while (q.value<10) {//get the value
System.out.println("Customer get "+q.get());
}
}
}
class Productor extends Thread{
Queue q;
public Productor(Queue q) {
this.q=q;
}
@Override
public void run() {
for (int i = 1; i <=10; i++) {
q.put(i);//product and show info
System.out.println("Productor put "+i);
}
}
}
class Queue{
int value;//count the mumber
boolean bFull=false;//whether the cup is full
public synchronized void put(int i){
if (!bFull) {
value=i;//fill the cup
bFull=true;//it is full
notifyAll();//notify other thread
try {
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 empty
notifyAll();//notify the Productor to put
return 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