欢迎光临散文网 会员登陆 & 注册

2年大厂经验,面试还是太紧张,90%的人不会写

2023-07-02 16:15 作者:Acer在写代码  | 我要投稿
package leecode;

import java.util.concurrent.Semaphore;

public class PrintAB {


    static Semaphore a= new Semaphore(1);
    static Semaphore b= new Semaphore(0);
    static class A implements Runnable{
        @Override
        public void run() {
             for(int i =0;i<=4;i++){
                 try {
                     a.acquire();
                     System.out.println("A");
                     b.release();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
             }
        }
    }
    static class B implements Runnable{
        @Override
        public void run() {
            for(int i =0;i<=4;i++){
                try {
                    b.acquire();
                    System.out.println("B");
                    a.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
    }
    public static void main(String[] args) {
        Thread t1 = new Thread(new A());
        Thread t2 = new Thread(new B());
        t1.start();
        t2.start();
    }
}


2年大厂经验,面试还是太紧张,90%的人不会写的评论 (共 条)

分享到微博请遵守国家法律