拋開面試八股文不談,兩種都本質(zhì)區(qū)別是線程獲取不到鎖時的狀態(tài)區(qū)別晒奕。
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();
}
}
結(jié)果
這兩狀態(tài)的本質(zhì)區(qū)別,blocked是主動脑慧,waiting是被動魄眉。blocked主動尋找監(jiān)視器繼續(xù)競爭鎖,waiting需要被動通知繼續(xù)執(zhí)行闷袒。blocked受操作系統(tǒng)控制坑律,waiting受JVM控制。
若有錯誤或者異議囊骤,歡迎指出~