Java中synchronized和ReentrantLock的
2024-10-20 本文已影响0人
尘与曦
抛开面试八股文不谈,两种都本质区别是线程获取不到锁时的状态区别。
Talk is cheap, show my code!
public class Main20 {
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws Exception {
test();
}
public static void test() throws InterruptedException {
Thread thread01 = new Thread(Main20::fun01);
Thread thread02 = new Thread(Main20::fun02);
Thread thread11 = new Thread(Main20::fun01);
Thread thread12 = new Thread(Main20::fun02);
thread01.start(); //线程先占着资源
thread02.start(); //线程先占着资源
TimeUnit.MILLISECONDS.sleep(1);
System.out.println("step01: " + thread01.getState()); //step01: RUNNABLE
System.out.println("step01: " + thread02.getState()); //step01: RUNNABLE
System.out.println("step01: " + thread11.getState()); //step01: NEW
System.out.println("step01: " + thread12.getState()); //step01: NEW
thread11.start(); //线程抢夺资源
thread12.start(); //线程抢夺资源
TimeUnit.MILLISECONDS.sleep(1);
System.out.println("step02: " + thread01.getState()); //step02: RUNNABLE
System.out.println("step02: " + thread02.getState()); //step02: RUNNABLE
System.out.println("step02: " + thread11.getState()); //step02: BLOCKED
System.out.println("step02: " + thread12.getState()); //step02: WAITING
thread01.interrupt(); //终止原线程
thread02.interrupt(); //终止原线程
TimeUnit.MILLISECONDS.sleep(1);
System.out.println("step03: " + thread01.getState()); //step03: TERMINATED
System.out.println("step03: " + thread02.getState()); //step03: TERMINATED
System.out.println("step03: " + thread11.getState()); //step03: RUNNABLE
System.out.println("step03: " + thread12.getState()); //step03: RUNNABLE
}
public synchronized static void fun01() {
long i = -100000000000L;
while (true) {
i++;
if (Thread.currentThread().isInterrupted()) {
break;
}
}
}
public static void fun02() {
lock.lock();
long i = -100000000000L;
while (true) {
i++;
if (Thread.currentThread().isInterrupted()) {
break;
}
}
lock.unlock();
}
}

这两状态的本质区别,blocked是主动,waiting是被动。blocked主动寻找监视器继续竞争锁,waiting需要被动通知继续执行。blocked受操作系统控制,waiting受JVM控制。
若有错误或者异议,欢迎指出~