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) {
            
        }
        
    }
    
    
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容