8_4、Java基本语法之线程的通信

一、问题的引入

        使用两个线程打印 1-100。线程1, 线程2交替打印?

二、解决问题涉及的方法

        涉及到的三个方法:

        1.wait():一旦执行此方法,那么调用此方法的线程就会进入阻塞状态,并释放同步监视器。            2.notify():一个线程执行此方法,会唤醒一个被wait的线程。如果有多个被wait的线程,那么唤醒优先级高的线程。

        3.notifyAll():一个线程执行此方法,会唤醒所有被wait的线程。

class Number implements Runnable{
    private int number = 1;
    private Object obj = new Object();

    @Override
    public void run() {
        while(true){
            synchronized (obj) {

                obj.notify();

                if(number <=100){
                    System.out.println(Thread.currentThread().getName() + ":" + number);
                    number++;
                    try {
                        //使得调用wait()的线程进入阻塞状态
                        obj.wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else{
                    break;
                }
            }
        }
    }
}


public class CommunicationTest {
    public static void main(String[] args) {
        Number num = new Number();

        Thread t1 = new Thread(num);
        Thread t2 = new Thread(num);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }
}

运行结果:

关于三个方法的说明:

1.wait()、notify()、notifyAll()这三个方法必须写在同步代码块或者同步方法中

2.wait()、notify()、notifyAll()这三个方法的调用者必须与同步代码块或者同步方法的同步监视器一致。 否则会报错:IllegalMonitorStateException。

3.wait()、notify()、notifyAll()这三个方法定义在java.lang.Objct类中。

三、经典例题

        生产者/消费者问题:生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处 取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图 生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通 知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如 果店中有产品了再通知消费者来取走产品。

这里可能出现两个问题: ①生产者比消费者快时,消费者会漏掉一些数据没有取到。 ②消费者比生产者快时,消费者会取相同的数据。

解决思路:

是否有多个线程?有,生产者、消费者

是否由共享数据?有,店员(产品)

是否有线程安全问题?有

如何解决线程安全问题?三种方式

//店员
class Clerk{
    private int numCount = 0;

    //生产产品
    public synchronized void produceProduct() {

        if (numCount < 20) {
            numCount++;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName() + "生产了第" + numCount +"个产品");
            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //消费产品
    public synchronized void cusumerProduct() {
        if(numCount>0){
            System.out.println(Thread.currentThread().getName() + "消费了第" + numCount + "个产品");
            numCount--;

            try {
                Thread.sleep(20);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            notify();
        }else{
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
//生产者
class Productor extends Thread{
    private Clerk clerk;

    public Productor(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.produceProduct();
        }
    }
}

//消费者
class Customer extends Thread{
    private Clerk clerk;

    public Customer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true) {
            clerk.cusumerProduct();
        }
    }
}



public class ProductTest {
    public static void main(String[] args) {

        Clerk c1 = new Clerk();


        Productor p1 = new Productor(c1);
        Customer cust = new Customer(c1);
        Customer cust2 = new Customer(c1);

        p1.setName("生产者");
        cust.setName("消费者1");
        cust2.setName("消费者2");

        p1.start();
        cust.start();
        cust2.start();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值