三线程轮流打印问题(四种方法,java)

问题

三个线程轮流打印数字:

线程一:1 2 3

线程二:4 5 6

线程三:7 8 9

线程一:10 11 12

。。。。。。。

此题网上有其他解法,不甚完美,在此补充

一、粗暴解发:通过自循环来检测是否该当前线程执行


/**
 * 依赖于线程自旋对当前状态的判断
 */
public class JavaThreadNumber3 {
    private static int atomic = 0;

    static class MyThread extends Thread {
        private volatile int index;

        public MyThread(String name, int i) {
            this.setName(name);
            this.index = i;
        }

        public boolean myTime() {
            return atomic == index;
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                if (atomic >= 36) {
                    return;
                }
                if (!myTime()) {// 自旋:非我的场次慢慢等
                    continue;
                }
                System.out.println(this.getName() + ":" + (atomic + 1));
                System.out.println(this.getName() + ":" + (atomic + 2));
                System.out.println(this.getName() + ":" + (atomic + 3));// 自增和打印两个操作在多线程情况下会出问题
                index += 9;// 下一个属于我的任务的状态
                atomic += 3;
                System.out.println("下一个执行状态:" + index);
            }
        }

        public static void main(String... args) {
            new MyThread("work-1", 0).start();
            new MyThread("work-2", 3).start();
            new MyThread("work-3", 6).start();
        }
    }
}

二、任务队列:每个线程都有属于自己的任务队列,该任务队列依赖于上一个线程来生产任务


/**
 * 依赖于每个线程自己的任务队列
 */
public class JavaThreadNumber5 {
    private static BlockingDeque[] deques = new LinkedBlockingDeque[]{
            new LinkedBlockingDeque(),
            new LinkedBlockingDeque(),
            new LinkedBlockingDeque()
    };
    private static Runnable runnable = new Runnable() {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + "=" + (++i));
            System.out.println(Thread.currentThread().getName() + "=" + (++i));
            System.out.println(Thread.currentThread().getName() + "=" + (++i));
        }
    };
    private static int i = 0;

    static class ThreadNumber extends Thread {
        private BlockingDeque myDeque, afterDeque;

        @Override
        @SneakyThrows
        public void run() {
            while (true) {
                Runnable runnable = (Runnable) this.myDeque.take();
                if (i == 36) {// 任务结束,回家
                    myDeque.clear();
                    produceToDeque();
                    return;
                }
                runnable.run();
                produceToDeque();
            }
        }

        public void produceToDeque() throws InterruptedException {
            this.afterDeque.put(runnable);
        }

        public ThreadNumber(int i, BlockingDeque myDeque, BlockingDeque afterDeque) {
            this.setName("work-" + i);
            this.myDeque = myDeque;
            this.afterDeque = afterDeque;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new ThreadNumber(1, deques[0], deques[1]).start();
        new ThreadNumber(2, deques[1], deques[2]).start();
        new ThreadNumber(3, deques[2], deques[0]).start();
        deques[0].put(runnable);
    }
}

三、lock.condition:当前线程执行完毕,唤醒下一个线程


/**
 * 依赖于lock.condition之间的相互唤醒
 */
public class JavaThreadNumber4 {
    private static int i = 0;
    private static Lock lock = new ReentrantLock();

    static class ThreadNumber extends Thread {
        private String work;
        private Condition a, b;
        private volatile boolean await;

        public ThreadNumber(int work, Condition a, Condition b) {
            this.work = "work-" + work;
            this.a = a;
            this.b = b;
        }

        public boolean isAwait() {
            return await;
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                lock.lock();
                try {
                    await = true;
                    a.await();
                    if (i == 36) {
                        b.signal();
                        return;
                    }
                    System.out.println(work + "=" + (++i));
                    System.out.println(work + "=" + (++i));
                    System.out.println(work + "=" + (++i));
                    b.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    public static void main(String[] args) {
        Condition a = lock.newCondition();
        Condition b = lock.newCondition();
        Condition c = lock.newCondition();

        ThreadNumber t1 = new ThreadNumber(1, a, b);
        ThreadNumber t2 = new ThreadNumber(2, b, c);
        ThreadNumber t3 = new ThreadNumber(3, c, a);

        t1.start();
        t2.start();
        t3.start();

        while (t1.isAwait()) {
            lock.lock();
            try {
                a.signal();
                break;
            } catch (Exception e) {
            } finally {
                lock.unlock();
            }
        }
    }
}

四、信号量:当前线程执行完毕,释放一个下一个线程运行所必需的信号量


/**
 * 依赖于上一个任务释放信号量
 */
public class JavaThreadNumber2 {
    private static int i = 0;

    static class ThreadNumber implements Runnable {
        private String work;
        private Semaphore a, b;

        public ThreadNumber(int work, Semaphore a, Semaphore b) {
            this.work = "work-" + work;
            this.a = a;
            this.b = b;
        }

        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                a.acquire();
                if (i == 36) {
                    b.release();
                    return;
                }
                System.out.println(work + "=" + (++i));
                System.out.println(work + "=" + (++i));
                System.out.println(work + "=" + (++i));
                b.release();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Semaphore a = new Semaphore(1);
        Semaphore b = new Semaphore(1);
        Semaphore c = new Semaphore(1);
        a.acquire(1);
        b.acquire(1);
        c.acquire(1);
        new Thread(new ThreadNumber(1, a, b)).start();
        new Thread(new ThreadNumber(2, b, c)).start();
        new Thread(new ThreadNumber(3, c, a)).start();
        a.release();
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值