交替打印ABC的多种方法

这是一道经典的笔试题,最近团队招聘,大家又把它翻出来了。这里稍微梳理下几种做法。
synchronized todo
ReentrantLock jdk1.5并发包引入了lock方式,通过ReentrantLock我们可以很方便的进行显式的锁操作,即获取锁和释放锁,对于同一个对象锁而言,同一时刻只可能有一个线程拿到了这个锁,此时其他线程通过lock.lock()来获取对象锁时都会被阻塞,直到这个线程通过lock.unlock()操作释放这个锁后,其他线程才能拿到这个锁。

package reentrantlock; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class LockABC {private static Lock lock = new ReentrantLock(); // 通过JDK5中的Lock锁来保证线程的访问的互斥 private static int state = 0; //通过state的值来确定是否打印public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; ) { lock.lock(); try { while (state % 3 == 0) { System.out.println("A"); state++; i++; } } finally { lock.unlock(); } } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; ) { lock.lock(); try { while (state % 3 == 1) { System.out.println("B"); state++; i++; } } finally { lock.unlock(); }}} }).start(); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 10; ) { lock.lock(); try { while (state % 3 == 2) { System.out.println("C"); state++; i++; } } finally { lock.unlock(); }}} }).start(); } }


ReentrantLock+Condition 生成多个对象锁,通过控制各个对象锁的获取和释放。
package reentrantlock; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class ConditionABC {private static Lock lock = new ReentrantLock(); static Condition conditionA = lock.newCondition(); static Condition conditionB = lock.newCondition(); static Condition conditionC = lock.newCondition(); private static String state = "A"; public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { lock.lock(); try { for (int i = 0; i < 10; i++) { if (!state.equals("A")){ conditionA.await(); } state = "B"; System.out.println("A"); conditionB.signal(); } }catch (Exception e){}finally { lock.unlock(); } } }).start(); new Thread(new Runnable() { @Override public void run() { lock.lock(); try { for (int i = 0; i < 10; i++) { if (!state.equals("B")){ conditionB.await(); } state = "C"; System.out.println("B"); conditionC.signal(); } }catch (Exception e){}finally { lock.unlock(); } } }).start(); new Thread(new Runnable() { @Override public void run() { lock.lock(); try { for (int i = 0; i < 10; i++) { if (!state.equals("C")){ conditionC.await(); } state = "A"; System.out.println("C"); conditionA.signal(); } }catch (Exception e){}finally { lock.unlock(); } } }).start(); } }

【交替打印ABC的多种方法】

    推荐阅读