优雅循环打印abc的方法

调用locksupport 可以 指定唤醒哪个线程特性
优雅实现线程循环打印

package threadStudy.base;

import java.util.concurrent.locks.LockSupport;

/**
 * @description:需要循环打印123 100次
 * @author: brave.chen
 * @create: 2020-03-05 20:49
 **/
public class ThreadLoop3 {
    private static class UserThread extends Thread {
        private Thread nextThread;
        private int n;

        public UserThread(int n) {
            this.n = n;
        }

        public Thread getNextThread() {
            return nextThread;
        }

        public void setNextThread(Thread nextThread) {
            this.nextThread = nextThread;
        }

        public int getN() {
            return n;
        }

        public void setN(int n) {
            this.n = n;
        }

        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                LockSupport.park();
                System.out.println("第" + (i + 1) + "次打印:" + n);
                LockSupport.unpark(nextThread);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {

        UserThread thread1 = new UserThread(1);
        UserThread thread2 = new UserThread(2);
        UserThread thread3 = new UserThread(3);
        thread1.setNextThread(thread2);
        thread2.setNextThread(thread3);
        thread3.setNextThread(thread1);

        // 依次开启a b c线程
        thread1.start();
        thread2.start();
        thread3.start();
        LockSupport.unpark(thread1);
    }
}

你可能感兴趣的:(优雅循环打印abc的方法)