java多线程快速入门(十三)

死锁产生的原因(必须有两个线程、必须有多个锁、锁之间必须有引用的过程)

package com.cppdy;

class MyThread9 implements Runnable {

    private Integer ticketCount = 100;
    private Object ob = new Object();
    public boolean falg = true;

    @Override
    public void run() {
        if (falg) {
            synchronized (ob) {
                while (ticketCount > 0) {
                    try {
                        Thread.sleep(50);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    synchronized (this) {
                        System.out
                                .println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
                        ticketCount--;
                    }
                }
            }
        } else {
            while (ticketCount > 0) {
                sale();
            }
        }
    }

    public synchronized void sale() {
        synchronized (ob) {
            if (ticketCount > 0) {
                try {
                    Thread.sleep(50);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "卖出了第:" + (100 - ticketCount + 1) + "张票。");
                ticketCount--;
            }
        }
    }
}

public class ThreadDemo9 {

    public static void main(String[] args) throws Exception {
        MyThread9 mt = new MyThread9();
        Thread thread1 = new Thread(mt, "窗口1");
        Thread thread2 = new Thread(mt, "窗口2");
        thread1.start();
        Thread.sleep(30);
        mt.falg = false;
        thread2.start();
    }

}

T1一直等待T2释放this锁

T2又一直等待T1释放ob锁

猜你喜欢

转载自www.cnblogs.com/cppdy/p/10015769.html