ALL > Computer and Education > courses > university courses > undergraduate courses > Operating System > ZSTU-(2020-2021)-1 > student homework > 2018329621186陈魏扬 >
homework_7 Version 0
👤 Author: by 1756894282qqcom 2020-12-15 05:35:22



  1. public class DieLock {

    public static Object t1 = new Object();
    public static Object t2 = new Object();

    public static void main(String[] args){
    new Thread(){
    @Override
    public void run(){
    synchronized (t1){
    System.out.println("Thread1 get t1");

    try {
    Thread.sleep(100);
    }catch (Exception e){

    }

    synchronized (t2){
    System.out.println("Thread2 get t2");
    }
    }
    }
    }.start();

    new Thread(){
    @Override
    public void run(){
    synchronized (t2){
    System.out.println("Thread2 get t2");

    try {
    Thread.sleep(100);
    }catch (Exception e){

    }

    synchronized (t1){
    System.out.println("Thread2 get t1");
    }
    }
    }
    }.start();
    }
    }


    Both wait for each other to release the lock they hold, and then wait until death...
    Sleep time is added in the middle to prevent the thread from obtaining the lock of two objects as soon as it runs.
    How to avoid deadlock?? ?
    Here are some suggestions:
    Avoid one thread acquiring multiple locks at the same time;
    Avoid a thread occupying multiple resources in the lock at the same time, and try to ensure that each lock occupies only one resource;
    Try timing lock, use lock.tryLock (timeout) instead of using internal locking mechanism;
    For database lock, locking and unlocking must be in one database connection, otherwise, unlocking failure will occur.

Please login to reply. Login

Reversion History

Loading...
No reversions found.