用两个线程,一个输出字母,一个输出数字,交替输出

 public class JoinThread extends Thread {

        static Thread threadA = null,threadB = null;
        public static void main(String[] args) throws InterruptedException {

            char[] a = "1234567".toCharArray();
            char[] b = "ABCDEFG".toCharArray();
            threadA = new Thread(()->{
                for (char c: a) {
                    System.out.println(c);
                    LockSupport.unpark(threadB); //叫醒threadB
                    LockSupport.park();  //threadA阻塞
                }
            }, "threadA");

            threadB = new Thread(()->{
                for (char c: b) {
                    LockSupport.park();  //threadB阻塞
                    System.out.println(c);
                    LockSupport.unpark(threadA); //叫醒threadB

                }
            }, "threadB");

            threadA.start();
            threadB.start();
        }
    }

猜你喜欢

转载自blog.csdn.net/weixin_39082432/article/details/114268363
今日推荐