Java_多线程(死锁)

死锁的思路是:多线程同时被阻塞,他们中一个或者全部都在等待某个资源被被释放.由与线程被无限期地阻塞,因此程序不可能正常终止.

public class Test4 {
    public static String obj1 = "obj1";
    public static String obj2 = "obj2";
  public static void main(String[] args) {
      sum s = new sum();
    Thread thread = new Thread(s);
    thread.start();
    func f = new func();
    Thread thread1 = new Thread(f);
    thread1.start();
    
}
}
class sum implements Runnable{

    @Override
    public void run() {
        try {
            System.out.println("开始");
            while (true) {
                synchronized (Test4.obj1) {
                    System.out.println("锁住obj1");
                    Thread.sleep(1000);
                    synchronized (Test4.obj2) {
                        System.out.println("锁住obj2");
                    }
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        }
        
        
    }
    


class func implements Runnable{

    @Override
    public void run() {
        try {
            System.out.println("开始");
            while (true) {
                synchronized (Test4.obj2) {
                    System.out.println("----锁住obj2");
                    Thread.sleep(2000);
                    synchronized (Test4.obj1) {
                        System.out.println("----锁住obj1");
                    }
                }
            }
        } catch (Exception e) {
            
        }
        
    }
    
    
}

你可能感兴趣的:(Java_多线程(死锁))