美文网首页
三个线程轮流打印1-100

三个线程轮流打印1-100

作者: Djbfifjd | 来源:发表于2020-06-19 09:36 被阅读0次

    一、synchronized关键字实现

    public class MyThread1 implements Runnable {
        private static Object lock = new Object();
        private static int count;
        private int no;
        public MyThread1(int no) {
            this.no = no;
        }
        @Override
        public void run() {
            while (true) {
                synchronized (lock) {
                    if (count > 100) {
                        break;
                    }
                    if (count % 3 == this.no) {
                        System.out.println(this.no + "--->" + count);
                        count++;
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    lock.notifyAll();
                }
            }
        }
    }
    

    二、ReentrantLock实现

    public class MyThread2 implements Runnable {
        private static ReentrantLock lock = new ReentrantLock();
        private static Condition condition = lock.newCondition();
        private static int count;
        private int no;
        public MyThread2(int no) {
            this.no = no;
        }
        @Override
        public void run() {
            while (true) {
                lock.lock();
                if (count > 100) {
                    break;
                } else {
                    if (count % 3 == this.no) {
                        System.out.println(this.no + "-->" + count);
                        count++;
                    } else {
                        try {
                            condition.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
                condition.signalAll();
                lock.unlock();
            }
        }
    }
    

    三、main函数

    public class ThreadTest {
        public static void main(String[] args) throws InterruptedException {
            Thread t1 = new Thread(new MyThread2(0));
            Thread t2 = new Thread(new MyThread2(1));
            Thread t3 = new Thread(new MyThread2(2));
            t1.start();
            t2.start();
            t3.start();
            t1.join();
            t2.join();
            t3.join();
        }
    }
    

    相关文章

      网友评论

          本文标题:三个线程轮流打印1-100

          本文链接:https://www.haomeiwen.com/subject/qezmxktx.html