Skip to content

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

@MyLinChi

Description

@MyLinChi

问题

一个线程同时启动,依次打印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);
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions