1. 程式人生 > 實用技巧 >java模擬死鎖

java模擬死鎖

使用synchronized 關鍵字,兩個執行緒分別佔用兩個string,然後sleep,兩個執行緒分別請求對方string、形成死鎖

package learning;

import java.util.Date;

class LockA extends Thread{
    public void run(){
        try{
            System.out.println(new Date().toString()+"Lock A 開始執行");
            while(true){
                synchronized (LockTest.obj1){
                    System.out.println(
new Date().toString()+"Lock A 鎖住 obj1"); Thread.sleep(3000); synchronized (LockTest.obj2){ System.out.println(new Date().toString()+"Lock A 鎖住 obj2"); Thread.sleep(60*1000); } } } }
catch (Exception e){ e.printStackTrace(); } } } class LockB extends Thread{ public void run(){ try{ System.out.println(new Date().toString()+"Lock B 開始執行"); while(true){ synchronized (LockTest.obj2){ System.out.println(
new Date().toString()+"Lock B 鎖住 obj2"); Thread.sleep(3000); synchronized (LockTest.obj1){ System.out.println(new Date().toString()+"Lock B 鎖住 obj1"); Thread.sleep(60*1000); } } } }catch (Exception e){ e.printStackTrace(); } } } class LockTest{ public static String obj1="obj1"; public static String obj2="obj2"; public static void main(String []arg){ LockA lockA=new LockA(); lockA.start(); LockB lockB=new LockB(); lockB.start(); } }