1. 程式人生 > >產生死鎖的一段程式碼

產生死鎖的一段程式碼

public class Main {
    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();
        new Thread(new Runnable() {
            public void run() {
                synchronized (obj1) {
                    System.out.println("thread1 鎖為 obj1");
                    try
{ Thread.sleep(1000);//為了保證執行緒thread2啟動獲得obj2鎖 } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj2) { System.out.println("thread1 鎖為 obj2"); } } } }).start(); new
Thread(new Runnable() { public void run() { synchronized (obj2) { System.out.println("thread2 鎖為 obj2"); synchronized (obj1) { System.out.println("thread2 鎖為 obj1"); } } } }).start(); } }