Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#字节客户端面试题(后补) #294

Open
MyLinChi opened this issue Sep 26, 2020 · 0 comments
Open

#字节客户端面试题(后补) #294

MyLinChi opened this issue Sep 26, 2020 · 0 comments

Comments

@MyLinChi
Copy link
Owner

问题

一个线程同时启动,依次打印A,B,C,D

求解

使用wait和notifyAll实现

package com.beatifulCoding;

public class ProducerAndConsumer {
    static volatile int step = 1;
    static Object lock = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread A = new Thread(()->{
            synchronized (lock){
                System.out.println("A");
                step = 2;
                lock.notifyAll();
            }
        });
        Thread B = new Thread(()->{
            synchronized (lock){
                while (step!=2){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("B");
                step = 3;
                lock.notifyAll();
            }
        });
        Thread C = new Thread(()->{
            synchronized (lock){
                while (step!=3) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("C");
                step = 4;
                lock.notifyAll();
            }
        });
        Thread D = new Thread(()->{
            synchronized (lock){
                while (step!=4){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("D");
                lock.notifyAll();
            }
        });
        A.start();
        B.start();
        C.start();
        D.start();

        Thread.sleep(1000);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant