Producer consumer issues

Time:2021-9-23

Producer consumer issues

Singleton pattern, sorting algorithm, producer and consumer, deadlock

Synchronized version wait notify

public class A {
    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0;i< 10;i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0;i < 10;i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();
    }
}

//Judgment, waiting, business, notification
class Data{
    //Resource class
    private int number = 0;
    //+1
    public synchronized void increment() throws InterruptedException {
        If (number! = 0) {// 0
            //Wait
            this.wait();
        }
        number ++;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //Notify other threads that I + 1 is over
        this.notifyAll();
    }
    //-1
    public synchronized void decrement() throws InterruptedException {
        If (number = = 0) {// 1 will be executed automatically
            //Wait
            this.wait();
        }
        number --;
        System.out.println(Thread.currentThread().getName()+"=>"+number);
        //Notify other threads that I -1'm done
        this.notifyAll();
    }
}

The problem exists. There are 4 threads a, B, C and D, false wake-up

Producer consumer issues

Change if to while judgment

Producer consumer issues of JUC version

Producer consumer issues

Find condition through lock
Producer consumer issues

  • code implementation
/**
 *Communication problem of thread time: producer and consumer wait for wake-up and notify wake-up
 *Threads alternately perform a and B operations, and the same variable num = 0
 * A:num+1
 * B:num-1
 */
public class B {
    public static void main(String[] args) {
        Data2 data = new Data2();

        new Thread(()->{
            for (int i = 0;i< 10;i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0;i < 10;i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0;i < 10;i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"c").start();

        new Thread(()->{
            for (int i = 0;i < 10;i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

//Judgment, waiting, business, notification
class Data2{
    //Resource class
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

//    condition.await(); // wait for
//    condition.signalAll(); // Wake up all
    //+1
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            While (number! = 0) {// 0
                //Wait
                condition.await();
            }
            number ++;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            //Notify other threads that I + 1 is over
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    //-1
    public void decrement() throws InterruptedException {
        lock.lock();
        try {
            While (number = = 0) {// 1 will be executed automatically
                //Wait
                condition.await();
            }
            number --;
            System.out.println(Thread.currentThread().getName()+"=>"+number);
            //Notify other threads that I -1'm done
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

Any new technology definitely not only covers the original technology, advantages and supplements

Condition accurate notification and wake-up threads

Producer consumer issues

  • Code test
/**
 *A calls B after execution, B calls C after execution, and C calls a after execution
 */
public class C {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printA();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printB();
            }
        },"B").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data3.printC();
            }
        },"C").start();
    }
}

class Data3 {
    //Resource class
    private Lock lock = new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();
    private int number = 1; //1A 2B 3C

    public void printA() {
        lock.lock();
        try {
            //Business code, judgment - > execution - > notification
            while (number != 1) {
                //Wait
                condition1.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>AAAAAA");
            //Wake up the designated person, B
            number = 2;
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }

    public void printB() {
        lock.lock();
        try {
            //Business code, judgment - > execution - > notification
            while (number !=2) {
                //Wait
                condition2.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>BBBBBB");
            //Wake up C
            number = 3;
            condition3.signal();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            //Business code, judgment - > execution - > notification
            while (number != 3) {
                condition3.await();
            }
            System.out.println(Thread.currentThread().getName()+"=>CCCCCC");
            number = 1;
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]