park unpark 原理与应用

2020-06-02  本文已影响0人  抬头挺胸才算活着

原理有点像二值信号量

_counter=0的时候调用park

无力抵挡伤害,只好阻塞


线程阻塞的时候调用unpark

补血,但是为了救活,很快被消耗


应用

Park在写的时候要拿到线程,然后进行操作,线程多的话可能需要将线程放在数组里面;
需要等待同步的需要先调用park等待;

/**
 * @program: offer
 * @description:
 * @author: liyuecheng
 * @create: 2020-06-02 23:33
 **/
public class OrderControlUsingPark {
    private static boolean hasPrint1;

    public static void main(String[] args) {
        Thread print1Thread;
        Thread print2Thread;

        print2Thread = new Thread(() -> {
            LockSupport.park();
            System.out.println("print2");
        });

        print1Thread = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("print1");
            hasPrint1 = true;
            LockSupport.unpark(print2Thread);
        });

        print2Thread.start();
        print1Thread.start();
    }
}
public class JiaoTiShuChuUsingPark {
    private static Thread[] threads;

    private static void print(String string) {
        for (int i = 0; i < 5; i++) {
            LockSupport.park();
            System.out.println(string);
            LockSupport.unpark(nextThread());
        }
    }

    private static Thread nextThread(){
        Thread current = Thread.currentThread();
        int index = 0;
        for (int i = 0; i < threads.length; i++) {
            if(threads[i] == current) {
                index = i;
                break;
            }
        }

        if(index < threads.length - 1) {
            return threads[index+1];
        } else {
            return threads[0];
        }
    }

    private static void start() {
        for (Thread thread : threads) {
            thread.start();
        }
        LockSupport.unpark(threads[0]);
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            print("a");
        }, "a-thread");

        Thread thread2 = new Thread(() -> {
            print("b");
        }, "b-thread");

        Thread thread3 = new Thread(() -> {
            print("c");
        }, "c-thread");

        threads = new Thread[]{thread1, thread2, thread3};
        start();
    }

}
上一篇下一篇

猜你喜欢

热点阅读