ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

多线程打印宝典

2021-05-14 22:03:48  阅读:165  来源: 互联网

标签:Thread int lock 打印 宝典 private static new 多线程


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

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

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

标签:Thread,int,lock,打印,宝典,private,static,new,多线程
来源: https://www.cnblogs.com/zyxhangzhou/p/14770022.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有