/////////////////////////////////////////////////////////// Test.java ²âÊÔ´úÂë
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
//ÈçÓжà³öÉú²ú´Ë´¦q±ØÐëΪµ¥Àýģʽ£¬Èç×îºóÄǸöÔ´Îļþ£¡
QueueThread q = new QueueThread();
// Æô¶¯10ÌõÏû·ÑÏß³Ì
for (int i = 0; i < 5; i++) {
Consumer c = new Consumer(q);
c.start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// for (int i = 0; i < 50; i++) {
Producer p = new Producer(q);
p.setStr("Éú²úÏ̲߳úÉúggggggggg ");
p.start();
// }
// ·ÇÉú²úÏ̲߳úÉúÊý¾Ý
for (int i = 0; i < 50; i++) {
q.put(" ·ÇÉú²úÏ̲߳úÉúÊý¾Ý " + i);
}
}
}
/////////////////////////////////////////// QueueThread.java Ï̳߳Ø
import java.util.LinkedList;
public class QueueThread {
final static int MaxLength = 10;// µÈ´ý¶ÓÁдóС
private static LinkedList thread_pool = null;
public QueueThread() {
synchronized (this) {
if (thread_pool == null) {
System.out.println("³õʼ»¯");
thread_pool = new LinkedList();
}
}
}
/**
* ÅжÏÊÇ·ñÒÑÂú
*
* @return
*/
public boolean isFull() {
return thread_pool.size() >= MaxLength true : false;
}
/**
* ÅжÏÊÇ·ñΪ¿Õ
*
* @return
*/
public boolean isEmpty() {
return thread_pool.isEmpty();
}
/**
* Éú²úģʽ£º²åÈëÊý¾Ýµ½¶ÓÁÐ
*
* @param obj
*/
public synchronized void put(Object obj) {
while (isFull()) {
try {
System.out.println("ÂúÁ˵ȴý¡£¡£¡£¡£¡£¡£");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Èç¹ûûÂú£¬²åÈë
// ²åÈëµ½¶Óβ
System.out.println("ûÂú¡£¡£¡£¡£¡£");
thread_pool.addLast(obj);
notify();// notifyAll();
}
/**
* Ïû·Ñģʽ£º´Ó¶ÓÁÐÀïÃæÈ¡³öÒ»¸ö¶ÔÏó
*
* @return
*/
public synchronized Object get() {
// Èç¹ûÊǿյÄÔòµÈ´ý
while (isEmpty()) {
System.out.println("ûÊý¾ÝµÈ´ý¡£¡£¡£¡£¡£");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("ÓÐÊý¾Ý£¬¸É»î¡£¡£¡£¡£¡£");
notify();
return thread_pool.removeFirst();
}
}
///////////////////////////////////////// Consumer.java
/**
* Ïû·ÑÏß³Ì
*
* @author Mygia.mai
*
*/
public class Consumer extends Thread {
private QueueThread q;
public Consumer(QueueThread q){
this.q=q;
}
public void run() {
while (true) {
System.out.println(getName() + " ¿ªÊ¼Ö´ÐÐÏû·Ñ£¡");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getName() + q.get());
System.out.println(getName() + " Ïû·Ñ½áÊø£¡");
}
}
}
////////////////////////////////// Producer.java Éú²úÕßÏß³Ì
public class Producer extends Thread {
QueueThread q;
private String str;
Producer(QueueThread q) {
this.q = q;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public void run() {
for (int i = 0; i < 50; i++)
q.put(str + i);
}