多线程打印宝典

Posted zyxhangzhou

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程打印宝典相关的知识,希望对你有一定的参考价值。

典中典多线程打印题,我来归纳一下:

  1. 三个线程分别打印 A,B,C,要求这三个线程一起运行,打印 n 次,输出形如“ABCABCABC....”的字符串

使用Semaphore

这一招也是我最喜欢的,简单无脑

public class Main {
    private static final Semaphore[] s = {new Semaphore(1), new Semaphore(0), new Semaphore(0)};
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n = input.nextInt();
        input.close();
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    s[0].acquire();
                    System.out.print(\'A\');
                    s[1].release();
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    s[1].acquire();
                    System.out.print(\'B\');
                    s[2].release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        new Thread(() -> {
            try {
                for (int i = 0; i < n; i++) {
                    s[2].acquire();
                    System.out.print(\'C\');
                    s[0].release();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }
}

使用ReentrantLock

public class Main {
    private final int times;
    private int status;
    private static final Lock lock = new ReentrantLock();
    private static final Condition c1 = lock.newCondition();
    private static final Condition c2 = lock.newCondition();
    private static final Condition c3 = lock.newCondition();

    public Main(int times) {
        this.times = times;
    }

    public static void main(String[] args) {
        Main main = new Main(10);
        new Thread(() -> {
            main.printLetter(0, c1, c2);
        }, "A").start();
        new Thread(() -> {
            main.printLetter(1, c2, c3);
        }, "B").start();
        new Thread(() -> {
            main.printLetter(2, c3, c1);
        }, "C").start();
    }

    public void printLetter(int targetStatus, Condition current, Condition next) {
        for (int i = 0; i < times; ) {
            lock.lock();
            try {
                while (status % 3 != targetStatus) {
                    current.await();
                }
                ++status;
                ++i;
                System.out.print(Thread.currentThread().getName());
                next.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

使用Lock/Condition的话虽说代码比Semaphore复杂,但是可以做到精准控制,比如,AA 打印 5 次,BB 打印10 次,CC 打印 15 次,重复 10 次

public class Main {
    private int status;
    private static final Lock lock = new ReentrantLock();
    private static final Condition c1 = lock.newCondition();
    private static final Condition c2 = lock.newCondition();
    private static final Condition c3 = lock.newCondition();

    public static void main(String[] args) {
        Main main = new Main();
        new Thread(() -> {
            for (int i = 0; i < 5; i++)
                main.printLetter(0, c1, c2, 5);
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++)
                main.printLetter(1, c2, c3, 10);
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                main.printLetter(2, c3, c1, 15);
                System.out.print(" | ");
            }
        }, "C").start();
    }

    public void printLetter(int targetStatus, Condition current, Condition next, int times) {
        lock.lock();
        try {
            while (status % 3 != targetStatus) {
                current.await();
            }
            for (int i = 0; i < times; i++) {
                System.out.print(Thread.currentThread().getName());
            }
            ++status;
            next.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

gsxxbQ.png

使用 LockSupport

LockSupport 是 JDK 底层的基于 sun.misc.Unsafe 来实现的类,用来创建锁和其他同步工具类的基本线程阻塞原语。它的静态方法unpark()park()可以分别实现阻塞当前线程和唤醒指定线程的效果,所以用它解决这样的问题会更容易一些。

public class Main {
    private static final Thread[] threads = new Thread[3];
    public static void main(String[] args) {
        threads[0] = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                System.out.print(Thread.currentThread().getName());
                LockSupport.unpark(threads[1]);
                LockSupport.park();
            }
        }, "A");
        threads[1] = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                LockSupport.park();
                System.out.print(Thread.currentThread().getName());
                LockSupport.unpark(threads[2]);
            }
        }, "B");
        threads[2] = new Thread(() -> {
            for (int i = 0; i < 50; i++) {
                LockSupport.park();
                System.out.print(Thread.currentThread().getName());
                LockSupport.unpark(threads[0]);
            }
        }, "C");
        for (Thread t : threads) {
            t.start();
        }
    }
}

这种方法与Semaphore有异曲同工之妙,也是十分简单的一种方式!

  1. 交替打印奇偶数字
public class Main {
    private int status;
    private static final Lock lock = new ReentrantLock();
    private static final Condition c1 = lock.newCondition();
    private static final Condition c2 = lock.newCondition();

    public static void main(String[] args) {
        Main main = new Main();
        new Thread(() -> {
            main.printNum(100, 0, c1, c2);
        }, "even:").start();
        new Thread(() -> {
            main.printNum(100, 1, c2, c1);
        }, "odd:").start();
    }

    public void printNum(int times, int targetStatus, Condition current, Condition next) {
        while (status < times) {
            lock.lock();
            try {
                while (status % 2 != targetStatus) {
                    current.await();
                }
                System.out.print(Thread.currentThread().getName() + status + " ");
                ++status;
                next.signal();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}

gy90R1.png

使用LockSupport一如既往的简单易懂。

public class Main {
    private static final Thread[] threads = new Thread[2];
    public static void main(String[] args) {
        threads[0] = new Thread(() -> {
            // 注意上下的循环steps一定要是一样的,否则程序不会运行结束
            for (int i = 0; i < 100; i += 2) {
                System.out.print(Thread.currentThread().getName() + i + " ");
                LockSupport.unpark(threads[1]);
                LockSupport.park();
            }
        }, "even:");
        threads[1] = new Thread(() -> {
            for (int i = 1; i <= 100; i += 2) {
                LockSupport.park();
                System.out.print(Thread.currentThread().getName() + i + " ");
                LockSupport.unpark(threads[0]);
            }
        }, "odd:");
        for (Thread t : threads) {
            t.start();
        }
    }
}

------------恢复内容结束------------

以上是关于多线程打印宝典的主要内容,如果未能解决你的问题,请参考以下文章

Java面试宝典线程安全问题|线程死锁的出现|线程安全的集合类

JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段

[Interview]Java 面试宝典系列之 Java 多线程

多线程 Thread 线程同步 synchronized

Java多线程

多个用户访问同一段代码