方法:wait():让线程进入等待状态,直到其他线程调用notify()或notifyAll()或者到了按指定时间。
notify():唤醒在此对象监视器上等待的单个线程。
notifyAll():唤醒在此对象监视器上等待的所有线程。
经典模型:生产者-消费者
//产品类
public class Product {
String name;
int id;
public Product(String name, int id) {
this.name = name;
this.id = id;
}
public String toString() {
return "Product [name=" + name + ", id=" + id + "]";
}
}
//生产者
public class Produter implements Runnable {
ProductBox box;
Thread t;
Produter(ProductBox box) {
this.box = box;
t = new Thread(this);
t.start();
}
public void run() {
for (int i = 1; i < 11; i++)
box.put(new Product("产品", i));// 生产
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费者
public class Consumer implements Runnable {
ProductBox box;
Thread t;
public Consumer(ProductBox box) {
this.box = box;
t = new Thread(this);
t.start();
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
box.get();// 消费
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//缓存产品
public class ProductBox {
Product box[] = new Product[5];// 缓存数组
int index = 0;
// 生产产品
public synchronized void put(Product p) {
if (index == 5) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
box[index++] = p;// 产品存入数组
System.out.println("生产:" + p);
notify();
}
// 消费产品
public synchronized Product get() {
if (index == 0) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Product p = box[--index];// 从数组取出产品
System.out.println("消费" + p);
notify();
return p;
}
}
//测试类
public class Test {
public static void main(String[] args) {
ProductBox box = new ProductBox();
new Produter(box);
new Consumer(box);
}
}