公平锁,但是输出的顺序不是t1,t2,t3,不是start的顺序执行吗?是开启之后到达执行的临界点顺序吗?临界点是什么?

package com.wjx;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
 * Description * * @author qianTo
 * @create 2021-01-28 20:46
 */public class ReentrantLockTest {
    // static Lock lock = new ReentrantLock();// 默认是非公平锁
 static Lock lock = new ReentrantLock(true);// 公平锁
 public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "正在运行~");
            } finally {
                lock.unlock();
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "正在运行~");
            } finally {
                lock.unlock();
            }
        }, "t2");
        Thread t3 = new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + "正在运行~");
            }finally {
                lock.unlock();
            }
        }, "t3");
        t1.start();
        t2.start();
        t3.start();
    }
}

最佳答案

start只是说线程可以运行了,具体什么时候什么顺序运行要看系统调度
所以输出顺序乱掉并不是锁出了问题,而是这三个线程执行的先后顺序并不一定是按照指定的顺序