描述
看到一道有意思的Java多线程面试题:要求两个线程交替打印a和b,且都打印50次,且a必须先打印。
这是一个关于线程同步的问题,显然有比较多的解法,比如利用synchronized、CyclicBarrier等来实现。下面是利用LockSupport的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class LockSupportDemo {
public static void main(String[] args) throws InterruptedException { Thread[] threads = new Thread[2];
threads[0] = new Thread(() -> { int i = 51; while (i-- > 1) { System.out.printf("%s %d---> %s%n", Thread.currentThread().getName(), i, 'a'); LockSupport.unpark(threads[1]); LockSupport.park(); }
});
threads[1] = new Thread(() -> {
int i = 51; while (i-- > 1) { LockSupport.park(); System.out.printf("%s %d---> %s%n", Thread.currentThread().getName(), i, 'b'); LockSupport.unpark(threads[0]); } });
Arrays.stream(threads).forEach(Thread::start); Thread.currentThread().join(1_000L); } }
|