原创

LockSupport实现线程通信

使用LockSupport的park()和unpark()方法去唤醒和阻塞线程的方式

示例代码

package com.debuggg.test1.main3;

import java.util.concurrent.locks.LockSupport;

public class LockSupportTest {
    static Thread t1,t2 = null;

    public static void main(String[] args) {
        char[] c1 = "12345678".toCharArray();
        char[] c2 = "ABCDEFGH".toCharArray();
        t1 = new Thread(() -> {
            for (char c : c1) {
                System.out.print(c);
                LockSupport.unpark(t2);
                LockSupport.park();
            }
        },"t1");

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

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

    }
}
正文到此结束
本文目录