首页 > 编程语言 > 详细

多线程打印宝典

时间:2021-05-15 00:30:47      阅读:28      评论:0      收藏:0      [点我收藏+]

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

  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();
        }
    }
}

技术分享图片

使用 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();
            }
        }
    }
}

技术分享图片

使用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();
        }
    }
}

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

多线程打印宝典

原文:https://www.cnblogs.com/zyxhangzhou/p/14770022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!