java多线程 循环交替打印ABC

交替打印100个字母/交替打印循环100次(一共300个)

  • 方案一.使用ReentrantLock + Condition

class ABCPrinter {//使用ReentrantLock + condition   //这里指的是三个线程总共打印100个
    private static final int PRINT_COUNT = 100;
    private static  volatile int count = 0;//静态保证类的所有对象都共享一份  volatile保证可见性,禁止指令重排序


    private static final Lock lock = new ReentrantLock();
    private static final Condition conditionA = lock.newCondition();
    private static final Condition conditionB = lock.newCondition();
    private static final Condition conditionC = lock.newCondition();

    public static void main(String[] args) {
        new Thread(() -> println("a", conditionA, conditionB)).start();
        new Thread(() -> println("b", conditionB, conditionC)).start();
        new Thread(() -> println("c", conditionC, conditionA)).start();
    }

    private static void println(String str, Condition current, Condition next) {
        try {
            lock.lock();
            while (count < PRINT_COUNT) {
                while (count % 3 != getThreadIndex(str)) {//套while循环 防止虚假唤醒
                    current.await();
                }
                if(count<PRINT_COUNT){//双重判断 防止最后阻塞的线程唤醒后 打印数字超过范围
                    System.out.println(Thread.currentThread().getName() + " : " + count +" : " + str);
                }
                count++;
                next.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    private static int getThreadIndex(String str) {
        switch (str) {
            case "a":
                return 0;
            case "b":
                return 1;
            case "c":
                return 2;
            default:
                throw new IllegalArgumentException("Invalid thread name");
        }
    }
}

效果展示

每个线程分别打印100个,交替打印

class ABCPrinter2 {//每个线程分别打印100个
    private static final int PRINT_COUNT = 100;
    private static final Lock lock = new ReentrantLock();
    private static final Condition conditionA = lock.newCondition();
    private static final Condition conditionB = lock.newCondition();
    private static final Condition conditionC = lock.newCondition();
    private static volatile int count = 0;

    public static void main(String[] args) {
        Runnable printA = () -> print("a", conditionA, conditionB);
        Runnable printB = () -> print("b", conditionB, conditionC);
        Runnable printC = () -> print("c", conditionC, conditionA);

        new Thread(printA).start();
        new Thread(printB).start();
        new Thread(printC).start();
    }

    private static void print(String str, Condition current, Condition next) {
        lock.lock();
        try {
            for (int i = 0; i < PRINT_COUNT; i++) {
                while (count % 3 != getThreadIndex(str)) {
                    current.await();
                }
                System.out.println(Thread.currentThread().getName() + " : " + i + " : " + str);
                count++;
                next.signal();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private static int getThreadIndex(String str) {
        switch (str) {
            case "a":
                return 0;
            case "b":
                return 1;
            case "c":
                return 2;
            default:
                throw new IllegalArgumentException("Invalid thread name");
        }
    }
}

效果展示

  • 方案二.使用Semaphore

class PrintABCUsingSemaphore { //使用semaphore
    private static Semaphore semaphoreA = new Semaphore(1);//通过permits控制 1表示允许一个线程共享
    private static Semaphore semaphoreB = new Semaphore(0);//为0 acquire()时直接阻塞
    private static Semaphore semaphoreC = new Semaphore(0);

    public static void main(String[] args) {
        Runnable printA = new PrintTask('A', semaphoreA, semaphoreB);
        Runnable printB = new PrintTask('B', semaphoreB, semaphoreC);
        Runnable printC = new PrintTask('C', semaphoreC, semaphoreA);

        Thread threadA = new Thread(printA);
        Thread threadB = new Thread(printB);
        Thread threadC = new Thread(printC);

        threadA.start();
        threadB.start();
        threadC.start();
    }

    static class PrintTask implements Runnable {
        private static final int TOTAL_COUNT = 100;
        private static volatile int count = 0;

        private char letter;
        private Semaphore currentSemaphore;
        private Semaphore nextSemaphore;

        public PrintTask(char letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
            this.letter = letter;
            this.currentSemaphore = currentSemaphore;
            this.nextSemaphore = nextSemaphore;
        }

        @Override
        public void run() {
            try {
                while (count < TOTAL_COUNT) {
                    currentSemaphore.acquire();//就算BC线程率先执行也会因为没有permits而阻塞在这里
                    if(count<TOTAL_COUNT){
                        System.out.println(Thread.currentThread().getName() + " : " + count + " : " + letter);
                        count++;
                    }
                    nextSemaphore.release();//让下一个允许执行的线程数量增加0->1
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

效果展示

每个线程分别打印100个,交替打印


class PrintABCUsingSemaphore2 {
    private static Semaphore semaphoreA = new Semaphore(1);
    private static Semaphore semaphoreB = new Semaphore(0);
    private static Semaphore semaphoreC = new Semaphore(0);
    private static final int TOTAL_COUNT = 100;

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> printLetter('A', semaphoreA, semaphoreB));

        Thread threadB = new Thread(() -> printLetter('B', semaphoreB, semaphoreC));

        Thread threadC = new Thread(() -> printLetter('C', semaphoreC, semaphoreA));

        threadA.start();
        threadB.start();
        threadC.start();
    }

    public static void printLetter(char letter, Semaphore currentSemaphore, Semaphore nextSemaphore) {
        try {
            int count = 0;//每个对象都有一份自己的
            while (count < TOTAL_COUNT) {//for循环也行
                currentSemaphore.acquire();
                System.out.println(Thread.currentThread().getName() + " : " + count + " : " + letter);
                count++;
                nextSemaphore.release();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

效果展示

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
java多线程交替打印ABC的实现方式有多种。一种常见的方式是使用synchronized关键字和wait/notify方法来实现线程的阻塞和唤醒。每个线程在打印完自己对应的字符后,调用notify方法唤醒下一个线程,并进入等待状态,等待下一个轮到自己打印字符。另一种方式是使用Lock和Condition来实现线程的阻塞和唤醒。每个线程在打印完自己对应的字符后,调用signal方法唤醒下一个线程,并进入等待状态,等待下一个轮到自己打印字符。下面是一种使用synchronized和wait/notify方法的实现方式的示例代码: ```java public class PrintABC { private static final Object lock = new Object(); private static int count = 0; private static int maxCount = 10; public static void main(String[] args) { Thread t1 = new Thread(() -> { print("A", 0); }); Thread t2 = new Thread(() -> { print("B", 1); }); Thread t3 = new Thread(() -> { print("C", 2); }); t1.start(); t2.start(); t3.start(); } private static void print(String str, int target) { while (count < maxCount) { synchronized (lock) { while (count % 3 != target) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(str); count++; lock.notifyAll(); } } } } ``` 以上代码使用了一个lock对象作为同步锁,count变量用于记录已经打印的字符数量。每个线程在打印字符之前,都会先判断count是否是自己对应的值,如果不是,则调用wait方法进入等待状态,直到被唤醒后再进行判断。当一个线程打印完字符后,会调用notifyAll方法唤醒其他等待中的线程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值