美文网首页
多线程实现轮询打印

多线程实现轮询打印

作者: Hey_Shaw | 来源:发表于2018-09-09 08:32 被阅读34次

创建两个线程,实现轮询打印1,-1,2,-2,3,-3,...,100,-100

  • 方法1
static final Object object = new Object();
private static void extractedForSyn() {
    // 线程1
    new Thread((Runnable) () -> {
        for (int i = 1; i <= 100; i++) {
            synchronized (object) {
                System.out.println(i);
                object.notify(); // 唤醒线程2
                try {
                    object.wait();// 线程1进入等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();

    // 线程2
    new Thread(() -> {
        for (int i = -1; i >= -100; i--) {
            synchronized (object) {
                System.out.println(i);
                object.notify();// 唤醒线程1
                try {
                    object.wait();// 线程2进入等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }).start();
}
  • 方法2
private static Lock lock = new ReentrantLock();
private static Condition condition1 = lock.newCondition();
private static Condition condition2 = lock.newCondition();
private static void extractedForLock() {
    // thread 1
    Thread t1 = new Thread(() -> {
        for (int i = 1; i <= 100; i++) {
            lock.lock();
            try {
                condition2.signal();
                System.out.println(i);
                condition1.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();
        }
    });

    // thread 2
    Thread t2 = new Thread(() -> {
        for (int i = -1; i >= -100; i--) {
            lock.lock();
            try {
                condition1.signal();
                System.out.println(i);
                condition2.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            lock.unlock();

        }
    });

    t1.setPriority(Thread.MAX_PRIORITY);
    t1.start();
    t2.start();
}

相关文章

  • 多线程实现轮询打印

    创建两个线程,实现轮询打印1,-1,2,-2,3,-3,...,100,-100 方法1 方法2

  • 爬虫课程笔记二

    第二次课程通过模拟登录微信,了解了轮询问和长轮询,通过多进程,多线程,协程等方式实现快速的爬虫。 轮询:我...

  • 多线程实现按序打印

    实现方式 1、使用Thread.join()方法;2、使用计数器CountDownLatch3、使用原子类Atom...

  • 今日份打卡 211/365

    技术文章实时服务器实现短轮询长轮询websocket

  • 使用NSTimer、GCD实现轮询

    第1种、NSTimer实现轮询 第2种、GCD方法轮询

  • 多线程

    1.使用NSThread实现多线程 1.1.线程的创建 打印出这个 还有下面两种创建线程的方式 1.2由多线程引发...

  • ECMAScript6基础学习教程(八)Promise

    JavaScript被设计为单线程(webWoker可以处理多线程),利用事件轮询机制,可以模拟出多线程效果,也就...

  • 多线程

    打印正在运行的多个线程 通过继承的方式实现线程 多线程共享全局变量 多线程共享全局变量 args参数 互斥锁 如果...

  • 多线程按顺序打印奇偶数

    看到一题目“多线程按顺序打印奇偶数”,网上的做法是通过synchronized,wait,notify来实现,其实...

  • Apollo 8 — ConfigService 异步轮询接口的

    源码 Apollo 长轮询的实现,是通过客户端轮询 /notifications/v2 接口实现的。具体代码在 c...

网友评论

      本文标题:多线程实现轮询打印

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