线程通信

来源:互联网 发布:锐捷交换机ip mac绑定 编辑:程序博客网 时间:2024/06/09 14:26

线程通信

wait():在其他线程调用此对象的notify()方法或者notifyAll()f方法前导致当前线程等待
notify():唤醒的单条线程
notifyAll():唤醒全部线程

package com.briup.day19;import javax.swing.table.TableColumn;/** * 生产者和消费者案例 * */public class ProducterConsumer {    public static void main(String[] args) {        Product product = new Product();        new Thread(new Producer(product)).start();        new Thread(new Consumer(product)).start();    }}/** * 生产者 * */class Producer implements Runnable {    private Product product;    private int x = 0;    public Producer(Product product) {        this.product = product;    }    @Override    public void run() {        while (true) {            synchronized (product) {                //生                if(product.isHave) {                    //有产品的,则生产者进入等待状态                    try {                          //等着,释放锁                        product.wait();                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }                if (x % 2 == 0) {                    // null null                    product.name = "包子";                    product.type = "肉";                } else if (x % 2 == 1) {                    product.name = "饺子";                    product.type = "素";                }                // 有产品了                product.isHave=true;                     //唤醒消费者                product.notify();                x++;            }        }    }}/** * 消费者 *  * @author lixiaojian * */class Consumer implements Runnable {    private Product product;    public Consumer(Product product) {        this.product = product;    }    @Override    public void run() {        while (true) {            synchronized (product) {                if (!product.isHave) {                    // 没产品了,消费者去等待                    try {                        // 消                        product.wait();                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }                System.out.println(product.name + "   " + product.type); // 包子 肉                // 没产品了                product.isHave = false;                // 唤醒生产者                product.notify();            }        }    }}/** * 产品 * */class Product {    String name;    String type;    boolean isHave = false;// 一开始是没产品的}

wait()和sleep()的区别是:sleep()方法不交出锁,相当于停止一定的时间而wait()这个方法是等待,锁交出其他的线程接到锁就可以运行

其实大家看了上面的案例不难发现,线程同步还是缜密的逻辑+同步线程

原创粉丝点击