Java線程死鎖代碼詳解
/** * @author hollis */ public class JStackDemo { public static void main(String[] args) { Thread t1 = new Thread(new DeadLockclass(true));//建立一個線程 Thread t2 = new Thread(new DeadLockclass(false));//建立另一個線程 t1.start();//啟動一個線程 t2.start();//啟動另一個線程 } } class DeadLockclass implements Runnable { public boolean falg;// 控制線程 DeadLockclass(boolean falg) { this.falg = falg; } public void run() { /** * 如果falg的值為true則調用t1線程 */ if (falg) { while (true) { synchronized (Suo.o1) { System.out.println("o1 " + Thread.currentThread().getName()); synchronized (Suo.o2) { System.out.println("o2 " + Thread.currentThread().getName()); } } } } /** * 如果falg的值為false則調用t2線程 */ else { while (true) { synchronized (Suo.o2) { System.out.println("o2 " + Thread.currentThread().getName()); synchronized (Suo.o1) { System.out.println("o1 " + Thread.currentThread().getName()); } } } } } } class Suo { static Object o1 = new Object(); static Object o2 = new Object(); }
import org.springframework.stereotype.Component; @Component public class SynchronizedTest { private static final Object lockA = new Object(); private static final Object lockB = new Object(); /** * ThreadA先獲取lockA,在獲取lockB */ private static class ThreadA extends java.lang.Thread { @Override public void run() { // 獲取臨界區A synchronized (lockA) { System.out.println("get lockA success"); // 模擬耗時操作 try { Thread.currentThread().setName("線程A"); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // 獲取臨界區B synchronized (lockB) { System.out.println("get lockB success"); } } } } /** * ThreadB先獲取lockB,在獲取lockA */ private static class ThreadB extends java.lang.Thread { @Override public void run() { // 獲取臨界區A synchronized (lockB) { System.out.println("get lockB success"); // 模擬耗時操作 try { Thread.currentThread().setName("線程B"); Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } // 獲取臨界區B synchronized (lockA) { System.out.println("get lockA success"); } } } } static { new ThreadA().start(); new ThreadB().start(); } }
總結
本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!