Java Multithreading (Case + Analysis) Intermediate Part: Thread Communication

Basic concepts of Java multithreading (case + analysis)
Java multithreading (case + analysis) advanced part: thread-safe lazy mode, thread lock problem
Java Multithreading (Case + Analysis) Intermediate Part: Thread Communication
Java multithreading (case + analysis) JDK5.0 new thread creation method

1. Example 1: Examples of thread communication

1. Use two threads to print 1-100. Thread 1, thread 2, alternate printing

Use wait and notify

package com.itzheng.java2;
/*
线程通信的例子:使用两个线程打印1-100。线程1,线程2,交替打印
说明:
 */
class Number implements  Runnable{
    
    
    private int number = 1;
    @Override
    public void run() {
    
    
        while (true){
    
    
            synchronized (this){
    
    
                notify();//唤醒等待的(wait)的线程
                if(number <= 100){
    
    
                    try {
    
    
                        Thread.sleep(10);
                    } 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 CommunicationTest {
    
    
    public static void main(String[] args) {
    
    
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

Insert picture description here

(1) Three methods involved in thread communication: (can only appear in synchronized code blocks and synchronized methods)

(1) wait(): Once this method is executed, the current thread enters the blocking state and releases the synchronization monitor.
(2) notify(): Once this method is executed, a thread that was wait() will be awakened.
If multiple threads are wait(), the one with the higher priority is awakened.
(3) notifyAll(): Once this method is executed, all a thread that was wait() will be awakened.

(2) Description:

(1) wait(), notify(), notifyAll() these three methods must be used in synchronous code blocks or synchronous methods, and they are called by this object

Insert picture description here

2. Any object as a synchronization monitor (define Object object)

(1) The caller of the three methods of wait(), notify(), notifyAll() must be a synchronous monitor in a synchronous code block or synchronous method.
Otherwise, there will be IllegalMonitorStateException异常
(2) wait(), notify(), notifyAll () These 3 methods are defined in the java.lang.Object class

package com.itzheng.java2;
/*
线程通信的例子:使用两个线程打印1-100。线程1,线程2,交替打印
 */
class Number implements  Runnable{
    
    
    private int number = 1;
    private Object obj = new Object();
    @Override
    public void run() {
    
    
        while (true){
    
    
            synchronized (obj){
    
    
                obj.notify();//唤醒等待的(wait)的线程
                if(number <= 100){
    
    
                    try {
    
    
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+":"+number);
                    number++;
                    try {
    
    
                        //使得调用如下wait()方法的线程进入阻塞状态
                        obj.wait();
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                }else {
    
    
                    break;
                }
            }
        }
    }
}
public class CommunicationTest {
    
    
    public static void main(String[] args) {
    
    
        Number number = new Number();
        Thread t1 = new Thread(number);
        Thread t2 = new Thread(number);
        t1.setName("线程1");
        t2.setName("线程2");
        t1.start();
        t2.start();
    }
}

Two, summary of the key and difficult points of multithreading

1. What are the similarities and differences between sleep() and wait()?

(1) The same point: Once the method is executed, the current thread can enter the blocking state.
(2) Differences:

1) The location of the two method declarations is different: sleep() is declared in the Thread class, and wait() is declared in the Object class.
2) The calling requirements are different: sleep() can be called in any required scene. wait() must be used in a synchronized code block or a synchronized method.
3) Questions about whether to release a synchronized monitor: If both methods are used in a synchronized code block or synchronized method, the sleep() method will not release the lock, wait( ) Will release the lock.

3. Example 2: Producer and consumer problem (application of thread communication)

●The producer (Productor) delivers the product to the clerk (Clerk), and the consumer (Customer) from the clerk

Removed product, the clerk can only hold a fixed number of products (for example: 20), if producers try to
produce more product, the clerk will call the producer pause, if there are vacancies store and then put the product through
knowledge production Consumers continue to produce: if there are no products in the store, the clerk will tell consumers to wait, and
if there are products in the store, they will notify consumers to take the products.

●Two problems may arise here:

➢ When the producer is faster than the consumer, the consumer will miss some data.
➢ When the consumer is faster than the producer, the consumer will fetch the same data.

Code implementation: sample questions (producer/consumer problem)

package com.itzheng.java2;

/*

线程通信的应用:金典例题:生产者/消费者问题

取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图
生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通
知生产者继续生产:如果店中没有产品了,店员会告诉消费者等- - 下,如
果店中有产品了再通知消费者来取走产品。

分析:
1、是否是多线程的问题?是,生产者线程,消费者线程
2、是否共享数据的问题?是,店员(或产品)
3、如何来解决线程的安全问题?同步机制,有三种方法
4、是否涉及到线程的通信?是
创建Clerk办事情的对象,作为同步监视器
创建Producer:生产者
创建Consumer:消费者
分别调用对应的start方法
两个线程分别调用Clerk当中的方法,同步监视器就是Clerk对象,只有当生产完毕后才可以执行消费
 */

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 consumerProduct() {
    
    
        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(getName() + ":" + ":开始生产产品。。。。");
        while (true){
    
    
            try {
    
    
                Thread.sleep(10);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            clerk.produceProduct();
        }
    }
}
class Consumer extends Thread{
    
    //消费者
    private Clerk clerk;

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

    @Override
    public void run() {
    
    
        System.out.println(getName() + ":" + ":开始消费产品。。。。");
        while (true){
    
    
            try {
    
    
                Thread.sleep(20);
            } catch (InterruptedException e) {
    
    
                e.printStackTrace();
            }
            clerk.consumerProduct();
        }
    }
}
public class ProductTest {
    
    
    public static void main(String[] args) {
    
    

        Clerk clerk = new Clerk();
        Producer p1 = new Producer(clerk);
        p1.setName("生产者一");

        Consumer c1 = new Consumer(clerk);
        c1.setName("消费者一");

        Consumer c2 = new Consumer(clerk);
        c2.setName("消费者二");

        p1.start();
        c1.start();
        c2.start();
    }
}

Insert picture description here

Basic concepts of Java multithreading (case + analysis)
Java multithreading (case + analysis) advanced part: thread-safe lazy mode, thread lock problem
Java Multithreading (Case + Analysis) Intermediate Part: Thread Communication
Java multithreading (case + analysis) JDK5.0 new thread creation method

Guess you like

Origin blog.csdn.net/qq_44757034/article/details/110800843