- 首先wait()和notify()并不是Thread类中的函数,而是Object类中的。但是面试中,问到线程时,经常问到wait(),notify()机制。
- 下面是一个wait()和notifyAll()的实例。
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
public class WaitNotifyTest{
private List synchedList;
public WaitNotifyTest() {
// 创建一个同步列表
synchedList = Collections.synchronizedList(new LinkedList());
}
// 删除列表中的元素
public void sendProduct() throws InterruptedException {
synchronized (synchedList) {
// 列表为空就等待
while (synchedList.isEmpty()) {
System.out.println(printTitle() + ":没有可搬运的产品,开始等待!");
synchedList.wait();
}
String element = (String) synchedList.remove(0);
System.out.println(printTitle() + ":开始搬运" + element + "!");
}
}
// 添加元素到列表
public void createProduct(String element) {
synchronized (synchedList) {
// 添加一个元素,并通知元素已存在
synchedList.add(element);
System.out.println(printTitle() + ":产品:'" + element + "'生产完成,发出提醒");
synchedList.notifyAll();
}
}
public static void main(String[] args) {
final WaitNotifyTest demo = new WaitNotifyTest();
Runnable runRemove = new Runnable() {
public void run() {
try {
demo.sendProduct();
} catch (Exception x) {
System.out.println("Exception thrown.");
}
}
};
Runnable runAdd = new Runnable() {
// 执行添加元素操作,并开始循环
public void run() {
System.out.println(printTitle() + ":开始生产...");
try {
Thread.sleep(2000); //模拟生产产品所消耗的时间
} catch (Exception e) {
e.printStackTrace();
System.out.println(printTitle() + ":" + e.getMessage());
}
demo.createProduct("ProjectA");
}
};
Thread t1 = new Thread(runRemove, "运输员");
t1.start();
Thread t2 = new Thread(runAdd, "生产员");
t2.start();
}
public static String getTime(long currentTime) {
return new SimpleDateFormat("HH:mm:ss").format(currentTime);
}
public static String printTitle() {
return getTime(System.currentTimeMillis()) + " " + Thread.currentThread().getName();
}
}
运行输出结果如下