线程LockSupport类的park和unpark方法使用

面试题:

用两个线程,一个输出字母,一个输出数字,交替输出1A2B3C4D5E.....26Z

LockSupport.park()让当前线程阻塞

LockSupport.unpark(t2)解锁t2线程

import java.util.concurrent.locks.LockSupport;

public class Test {
    static Thread t1=null,t2=null;
    public static void main(String[] args) {
        char [] nums="1234567".toCharArray();
        char [] chars="ABCDEFG".toCharArray();

        t1=new Thread(()->{
            for (char c:nums) {
                System.out.print(c);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        },"t1");

        t2=new Thread(()->{
            for (char c:chars) {
                System.out.print(c);
                LockSupport.park();
                LockSupport.unpark(t1);
            }
        },"t2");

        t1.start();
        t2.start();
    }
}

 

你可能感兴趣的:(#,Java面试题系列,#,线程)