Java死锁

public class ThreadSource implements Runnable{

    private String username;

    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void setFlag(String username){
        this.username = username;
    }

    @Override
    public void run() {
        if(username.equals("a")){
            synchronized (lock1){
                try {
                    System.out.println("username " + username);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2){
                    System.out.println("lock1 -> 进入lock2中了~");
                }
            }
        }

        if (username.equals("b")){
            synchronized (lock2){
                try {
                    System.out.println("username " + username);
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1){
                    System.out.println("lock2 -> 进入lock1中了~");
                }
            }
        }
    }
}
public class ThreadSourceMain {

    public static void main(String[] args) throws InterruptedException {
        ThreadSource threadSource = new ThreadSource();
        threadSource.setFlag("a");
        Thread t1 = new Thread(threadSource);
        t1.start();

        Thread.sleep(200);
        threadSource.setFlag("b");
        Thread t2 = new Thread(threadSource);
        t2.start();

    }
}

 使用jdk自带工具查看线程死锁,jps

 

使用jdk中的jstack -l 进程id,查看死锁具体详情,具体情况如下:

 

posted @ 2021-06-18 17:21  文所未闻  阅读(16)  评论(0编辑  收藏  举报