示例:生产和消费
线程间通讯和等待唤醒机制
*
* 是指多个线程在操作同一个资源,担是操作的动作不同
* wait():冻结线程
* notify():唤醒冻结中的第一个线程
* notifyAll():唤醒所有冻结的线程
* 它们都是使用在同步中,因为要对持有监视器(锁)的线程操作
* 所以要使用在同步中,因为只有同步才具有锁
*
* 担是wait,notify,notifyAll这些方法要定义在Object中呢?
* 因为这些方法在操作同步线程时,都必需要标识它们所操作线程持有的锁
* 只有同一个锁上的被等待的线程,可以被同一个锁上的notify唤醒
* 不可能对不同锁中的线程进行唤醒
* 也就是说,等待和唤醒必需是同一个锁。
* 需锁可能是任意对象,所以可以被任意对象调用的方法定义在Object类中。
要求:使用多线程,生产一个就消费一个
代码:
public class Thread_Demo4 {
public static void main(String[] args) {
// 实例化资源
Resouces res = new Resouces();
// 实例化生产和消费者
Producer pro = new Producer(res);
Consumer con = new Consumer(res);
// 创建两个生产线程和两个消费线程
Thread t1 = new Thread(pro);
Thread t2 = new Thread(pro);
Thread t3 = new Thread(con);
Thread t4 = new Thread(con);
// 启动线程
t1.start();
t2.start();
t3.start();
t4.start();
}
// 资源类
static class Resouces {
private String name;
private int count = 1;
private boolean isRn = false;
// 生产商品
public synchronized void set(String name) {
while (isRn) {
try {
// 冻结线程
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
// 设置生产名称和编号
this.name = name + "--" + count++;
System.out.println(Thread.currentThread().getName() + "--正在生产---"
+ this.name+"份");
isRn = true;
// 唤醒所有冻结的线程
this.notifyAll();
}
// 消费商品
public synchronized void out() {
while (!isRn) {
try {
// 冻结线程
this.wait();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()
+ "----已经消费------" + this.name+"份");
isRn = false;
// 在本线程冻结之前唤醒所有其它被冻结的线程
this.notifyAll();
}
}
// 生产者
static class Producer implements Runnable {
private Resouces res;
Producer(Resouces res) {
this.res = res;
}
public void run() {
while (true) {
res.set("汉堡");
}
}
}
// 消费者
static class Consumer implements Runnable {
private Resouces res;
Consumer(Resouces res) {
this.res = res;
}
public void run() {
while (true) {
res.out();
}
}
}
}
线程间通讯和等待唤醒机制
*
* 是指多个线程在操作同一个资源,担是操作的动作不同
* wait():冻结线程
* notify():唤醒冻结中的第一个线程
* notifyAll():唤醒所有冻结的线程
* 它们都是使用在同步中,因为要对持有监视器(锁)的线程操作
* 所以要使用在同步中,因为只有同步才具有锁
*
* 担是wait,notify,notifyAll这些方法要定义在Object中呢?
* 因为这些方法在操作同步线程时,都必需要标识它们所操作线程持有的锁
* 只有同一个锁上的被等待的线程,可以被同一个锁上的notify唤醒
* 不可能对不同锁中的线程进行唤醒
* 也就是说,等待和唤醒必需是同一个锁。
* 需锁可能是任意对象,所以可以被任意对象调用的方法定义在Object类中。