多线程实现轮询打印

创建两个线程,实现轮询打印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();
}

你可能感兴趣的:(多线程实现轮询打印)