1. 一道好玩有趣的面试题
Java求职中往往会碰到这样的面试题。请实现多线程交替打印0和1的程序。
看到这道题目,凭着程序员的第六感,我们很容易联想到消费者和生产者模式。他们之间有很大的相似之处啊。生产者线程负责往仓库生产物资,当仓库的物资物满为患的时候,阻塞线程停止生产,等待消费者线程消费物资后唤醒生产者线程。消费者线程负责从仓库拿出物资,当仓库没有物资的时候阻塞线程停止消费,等待生产者线程生产物资后唤醒消费者线程。这道题目不也是一样吗,有这样两类线程,一类线程打印0(下文称T0),一类线程打印1(下文称T1)。当满足打印0的条件下,T0打印0,同时阻塞T0并唤醒T1线程,在不满足打印0的条件下,T0就一直等待被T1唤醒。同理T1线程也是一样,在满足打印1的条件下,T1打印1,同时阻塞T1并唤醒T0线程,在不满足打印1的条件下,T1就一直等待被T0唤醒。要实现这样的功能我们很容易想到 wait()和notify()/notifyAll()方法。
- wait、notify以及notifyAll都是Object对象的方法,他们必须在被 synchronized 同步的方法或代码块中调用,否则会报错
- 调用wait方法会使该线程进入等待状态,并且会释放被同步对象的锁
- notify操作可以唤醒一个因执行wait而处于阻塞状态的线程,使其进入就绪状态,被唤醒的线程会去尝试着获取对象锁,然后执行wait之后的代码。如果发出notify操作时,没有线程处于阻塞状态,那么该命令会忽略。注意执行notify并不会马上释放对象锁,会等到执行完该同步方法或同步代码块后才释放
- notifyAll方法可以唤醒等待队列中等待同一共享资源的“全部”线程从等待状态退出,进入可运行状态。此时,优先级最高的那个线程优先执行,但也有可能是随机执行,这取决于JVM虚拟机的实现
2. 用synchronized配合wait() notify()/notifyAll()实现
下面我就用wait() notify()来实现交替打印功能
package com.peter.tips.lock; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * * Created by jiangbin on 2018/6/3. */ public class AlternatesUseWait { private static final Object lock = new Object(); private static int value; //判断当前应该打印的值 private static int getCurrentValue() { return value % 2; } public static void main(String[] args) { new Thread(new PrintZeroTask()).start(); new Thread(new PrintOneTask()).start(); } public static class PrintZeroTask implements Runnable { @Override public void run() { try { synchronized (lock) { while (true) {//这个while循环是让线程一直打印 while (getCurrentValue() == 1) {//大家一定要注意,这个while循环必不可少,少了这个while循环,这道面试题基本就是不及格 try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("0 " + Thread.currentThread().getName()); value = (value + 1) % 2;//value 交替 lock.notify();//唤醒打印1的线程 } } } finally { } } } public static class PrintOneTask implements Runnable { @Override public void run() { try { synchronized (lock) { while (true) { while (getCurrentValue() == 0) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("1 " + Thread.currentThread().getName()); value = (value + 1) % 2; lock.notify(); } } } finally { } } } }
至于打印的结果麻烦大家亲自运行下
2. 用Lock配合await() signal()/signalAll()实现
上一节我们讲到了java concurrent包的ReentrantLock。既然用synchronized 配合 wait/notify能实现。那么ReentrantLock 是不是也有类似wait/notify这样的实现呢。答案是有的。Lock接口有个Condition newCondition()方法,Condition是一个接口,它有await()和signal()/signalAll()。跟Object的wait() notify()/notifyAll()刚好一一对应。
package com.peter.tips.lock; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; /** * 多线程交替打印0和1 * Created by jiangbin on 2018/6/3. */ public class Alternates { private static ReentrantLock lock = new ReentrantLock(); private static Condition printOneCondition = lock.newCondition(); private static Condition printTwoCondition = lock.newCondition(); private static int value; private static int getCurrentValue() { return value % 2; } public static void main(String[] args) { new Thread(new PrintZeroTask()).start(); new Thread(new PrintOneTask()).start(); } public static class PrintZeroTask implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName()); lock.lock(); while (true) { while (getCurrentValue() == 1) { try { printOneCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("0 "+Thread.currentThread().getName()); value = (value + 1) % 2; printTwoCondition.signal(); } } finally { lock.unlock(); } } } public static class PrintOneTask implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName()); lock.lock(); while (true) { while (getCurrentValue() == 0) { try { printTwoCondition.await(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("1 "+Thread.currentThread().getName()); value = (value + 1) % 2; printOneCondition.signal(); } } finally { lock.unlock(); } } } }