JavaEE程序员JavaEE 学习专题

Java_多线程(死锁)

2017-09-24  本文已影响37人  Miss_差不多

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

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

上一篇下一篇

猜你喜欢

热点阅读