Loading...
墨滴

Xwenhui

2021/07/05  阅读:48  主题:前端之巅同款

多线程打印ABC

描述多线程交替打印A B C分别以Synchronized、ReentrantLock、Semaphore实现

这是一道常见的面试题,如果遇到需要手写代码这种题,首先是要理清思路,再就是尽量体现出代码风格,关键是顺序

Synchronized的实现

import lombok.SneakyThrows;
public class javaTestSynchronized {
    //信号标记
    private static volatile int state = 1;
    public static void main(String[] args) {
        Object o = new Object();
        new Thread(new printDepth(o,1,2,'A')).start();
        new Thread(new printDepth(o,2,3,'B')).start();
        new Thread(new printDepth(o,3,1,'C')).start();
    }
    static class printDepth implements Runnable{
        //定义循环次数
        private static final int COUNT =10;
        private Object lockObject;
        //当前 打印对象
        private int currPrint;
        //下一个 打印对象
        private int nextPrint;
        //打印的内容
        private char charPrint;
        public printDepth(Object lockObject, int currPrint, int nextPrint, char charPrint) {
            this.lockObject = lockObject;
            this.currPrint = currPrint;
            this.nextPrint = nextPrint;
            this.charPrint = charPrint;
        }
        @SneakyThrows
        @Override
        public void run() {
            synchronized(lockObject){
                for(int i=0;i<COUNT;i++){
                    while (currPrint!=state){
                        lockObject.wait();
                    }
                    System.out.println(Thread.currentThread().getName()+"  "+charPrint);
                    state = nextPrint;
                    lockObject.notifyAll();
                }
            }
        }
    }
}

ReentrantLock实现

import lombok.SneakyThrows;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class getContainerList {
    private static volatile int state = 1;
    public static void main(String[] args) {
        ReentrantLock lock  = new ReentrantLock();
        Condition conA = lock.newCondition();
        Condition conB = lock.newCondition();
        Condition conC = lock.newCondition();
        new Thread(new printABC(lock,conA,conB,'A',1)).start();
        new Thread(new printABC(lock,conB,conC,'B',2)).start();
        new Thread(new printABC(lock,conC,conA,'C',3)).start();
    }
    static class printABC implements Runnable{
        private Lock lock;
        private Condition currentPoint;
        private Condition nextPoint;
        private char printChar;
        private int targetState;
        public printABC(Lock lock, Condition currentPoint, Condition nextPoint, char printChar, int targetState) {
            this.lock = lock;
            this.currentPoint = currentPoint;
            this.nextPoint = nextPoint;
            this.printChar = printChar;
            this.targetState = targetState;
        }
        @SneakyThrows
        @Override
        public void run() {
            lock.lock();
            try {
                for(int i=0;i<10;i++){
                    while (state!=targetState)currentPoint.await();
                    System.out.println(Thread.currentThread().getName()+"  "+printChar);
                    state++;
                    if(state>3) state=1;
                    //nextPoint.signal();    //可能阻塞
                    nextPoint.signalAll();
                }
            } finally {
                lock.unlock();
            }
        }
    }
}

这回该到集合框架了


Semaphore实现

import lombok.SneakyThrows;
import java.util.concurrent.*;
public class getContainerList {
    private static final int COUNT = 10;
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(3310l, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>(10));
    public static void main(String[] args) throws InterruptedException {
        Semaphore seA = new Semaphore(1);//参数permits表示许可数目,即同时可以允许多少线程进行访问
        Semaphore seB = new Semaphore(0);
        Semaphore seC = new Semaphore(0);
        //阿里吧吧开发手册说了 不要用Executors创建线程池 !
        //ExecutorService executor = Executors.newFixedThreadPool(3);
        executor.submit(new printABC(seA,seB,'A'));
        executor.submit(new printABC(seB,seC,'B'));
        executor.submit(new printABC(seC,seA,'C'));
        executor.shutdown();
        executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    }
    static class printABC implements Runnable{
        private Semaphore currentPoint;
        private Semaphore nextPoint;
        private char printChar;
        public printABC(Semaphore currentPoint, Semaphore nextPoint, char printChar) {
            this.currentPoint = currentPoint;
            this.nextPoint = nextPoint;
            this.printChar = printChar;
        }
        @SneakyThrows
        @Override
        public void run() {
            for(int i =0;i<COUNT;i++){
                //获取当前的锁
                currentPoint.acquire(); //获取一个许可
                System.out.println(Thread.currentThread().getName()+"  "+printChar);
                nextPoint.release(); //释放一个许可
            }
        }
    }
}

Xwenhui

2021/07/05  阅读:48  主题:前端之巅同款

作者介绍

Xwenhui