多线程(十一)---等待唤醒机制原理

多线程(十一)---等待唤醒机制原理

1.代码演示

//多线程中通讯.多个线程都在处于同一资源,可是处理的任务却不同
//生产者,生产一个面包
//消费者,消费一个面包.
class Res {

    private int count = 1;// 面包数量
    private String name;
    boolean flag;// 定义标记

    // 提供了商品的赋值的方法
    public synchronized void set(String name){

        // 判断标记 true 执行wait.等待,为false.就生产
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        this.name = name+"----"+count;

        count++;
        System.out.println(Thread.currentThread().getName()+"--生产者----"+this.name);
        // 生产完毕,将标记改成true
        flag = true;
        // 唤醒消费者
        this.notify();
    }

    // 提供了商品获取的方法
    public synchronized void get(){

        if(!flag){
            try {
                wait();
            } catch (InterruptedException e) {
            }
        }

        System.out.println(Thread.currentThread().getName()+"---消费者---"+this.name);
        // 将标记改成false
        flag = false;

        // 唤醒提供者
        this.notify();
    }
}

/**
 * 消费者
 */
class Customer implements Runnable {
    private Res r;

    Customer(Res r){
        this.r = r;
    }

    public void run(){
        while (true) {
            r.get();
        }
    }
}

/**
 * 生产者
 */
class producer implements Runnable {

    private Res r;

    producer(Res r){
        this.r = r;
    }

    public void run(){
        while (true) {
            r.set("面包");
        }
    }
}

public class WaitAndNotifyDemo {
    public static void main(String[] args) {
        // 1.建立线程资源
        Res r =  new Res();
        // 2.建立线程任务
        producer p = new producer(r);
        Customer c = new Customer(r);
        // 3.执行线程
        new Thread(p).start();
        new Thread(c).start();

    }
}

2.等待唤醒讲解

wait():该方法能够让线程处于冻结状态,并将线程临时存储到线程池中

notify():唤醒指定线程池中任意一个线程

notifyAll():唤醒指定线程池中全部线程

这些方法必须使用在同步中,若是不是在同步中会出现(IllegalMonitorStateException 异常),由于它们操做的同步锁上的线程异常

在使用这些方法时,必须标识它们所属于的锁。标识方式就是 锁对象.wait(),锁对象.notify(),锁对象.notifyAll()相同锁的notify(),能够获取相同锁的wait();

相关文章
相关标签/搜索