JAVA学习笔记(多线程五)——线程的通信

JAVA学习笔记(多线程五)——线程的通信

下面通过一些例子来说明线程通信(线程通信就是解决死锁问题)

下面是会用到的一些方法:

  • wiat():一旦执行此方法,当前线程就进入阻塞状态,并释放同步监视器。

  • notify():一旦执行此方法,就会唤醒被wait的一个线程。如果有多个线程被wait,就唤醒优先级高的那个。

  • notifyAll():—旦执行此方法,就会唤醒所有被wait的线程。

说明:

  1. wait(),notify(),notifyALl()三个方法必须使用在同步代码块或同步方法中。(锁(Lock)有专门的方法)

  2. wait(),notify(),notifyALl()三个方法的调用者必须是同步代码块或同步方法中的同步监视器; 否则,会出现IllegalMonitorStateException异常。

  3. wait(),notify(),notifyAll()三个方法是定义在java.Lang.object类中。

常见线程里的面试题: sLeep()和wait()的异同?

相同点:

  • 一旦执行方法,都可以使得当前的线程进入阻塞状态。

不同点:

  1. 两个方法声明的位置不同: Thread类中声明sLeep() , object类中声明wait()

  2. 调用的要求不同: sleep()可以在任何需要的场景下调用。wait()必须使用在同步代码块或者同步方法中

  3. 关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sLeep()不会释放锁,wait()会释放锁。

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

class NumberPrinter implements Runnable{
    
    
    private int number=1;
    @Override
    public void run() {
    
    
        while (true){
    
    
            synchronized (this){
    
    
                //
                notify();
                if (number<=100){
    
    
                    try {
    
    
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"打印:"+number);
                    number++;
                    try {
    
    
                        //使用wait()方法使线程阻塞
                        wait();
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }else {
    
    
                    break;
                }
            }
        }
    }
}
public class TheadCommunicationTest {
    
    
    public static void main(String[] args) {
    
    
        NumberPrinter numberPrinter=new NumberPrinter();
        Thread thread1=new Thread(numberPrinter);
        Thread thread2=new Thread(numberPrinter);
        thread1.setName("线程一");
        thread2.setName("线程二");
        thread1.start();
        thread2.start();
    }
}

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

分析:

  1. 是否是多线程问题?是,生产者线程,消费者线程
  2. 是否有共享数据?是,店员(或产品>
  3. 如何解决线程的安全问题?同步机制,有三种方法
  4. 是否涉及线程的通信?是
class Clerk{
    
    
    private int productCount=0;
    //生产产品
    public synchronized void produceProduct() {
    
    
        if (productCount<20) {
    
    
            productCount++;
            System.out.println(Thread.currentThread().getName()+"开始生产第"+productCount+"产品");
            //唤醒一个线程(消费)
            notify();
        }else {
    
    
            try {
    
    
                //等待(阻塞生产)
                wait();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
    //消费产品
    public synchronized void consumeProduct() {
    
    
        if (productCount > 0) {
    
    
            System.out.println(Thread.currentThread().getName()+"开始消费第"+productCount+"产品");
            productCount--;
            //唤醒一个线程(线程)
            notify();
        }else {
    
    
            try {
    
    
                //等待(阻塞消费)
                wait();
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
        }
    }
}
class Producer extends Thread{
    
    
    private Clerk clerk;

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

    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+"开始生产产品");
        while (true){
    
    
            try {
    
    
                Thread.sleep(10);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}
class Customer extends Thread{
    
    
    private Clerk clerk;
    public Customer(Clerk clerk){
    
    
        this.clerk=clerk;
    }
    @Override
    public void run() {
    
    
        System.out.println(Thread.currentThread().getName()+"开始消费产品");
        while (true){
    
    
            try {
    
    
                Thread.sleep(20);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}
public class ProductTest {
    
    
    public static void main(String[] args) {
    
    
        Clerk clerk=new Clerk();
        Producer producer1=new Producer(clerk);
        producer1.setName("生产者一");
        Customer customer1=new Customer(clerk);
        Customer customer2=new Customer(clerk);
        customer1.setName("消费者一");
        customer2.setName("消费者二");
        producer1.start();
        customer1.start();
        customer2.start();
    }
}

猜你喜欢

转载自blog.csdn.net/m0_46450708/article/details/119041512