package TestPac;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class NotifyWaitThread {
LinkedList<String> linkedList = new LinkedList<String>();
/**
* @param args
*/
public static void main(String[] args) {
NotifyWaitThread notifyWaitThread = new NotifyWaitThread();
Thread notifyThread = new Thread(notifyWaitThread.new NotifyThread());
notifyThread.start();
for (int i = 0; i < 5; i++) {
Thread waitThread = new Thread(notifyWaitThread.new WaitThread());
waitThread.start();
}
}
class NotifyThread implements Runnable {
@Override
public void run() {
while (true) {
ProduceCommand();
try {
TimeUnit.MILLISECONDS.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void ProduceCommand() {
synchronized (linkedList) {
for (int i = 0; i < 5; i++) {
linkedList.add(new SimpleDateFormat("HH:mm:ss:SSS")
.format(new Date()));
}
linkedList.notifyAll();
}
}
}
class WaitThread implements Runnable {
@Override
public void run() {
while (true) {
String commandString = GetCommand();
System.out.println(Thread.currentThread().getName() + " "
+ commandString);
}
}
private String GetCommand() {
synchronized (linkedList) {
while (linkedList.size() == 0) {
try {
System.out.println(Thread.currentThread().getName()
+ " is waiting");
// wait() 继续执行的前提是获得了linkedList的锁
linkedList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return linkedList.poll();
}
}
}
}