java使用lock实现一个简单的死锁程序

时间:2021-11-30 20:51:10
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Four {
    public static void main(String[] args) {
        final Service1 myService = new Service1();
        for(int i = 0 ; i < 10 ; i ++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        myService.push();
                    }
                }
            });
            thread.start();
        }
        for(int i = 0 ; i < 10 ; i ++){
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true){
                        myService.pop();
                    }
                }
            });
            thread.start();
        }
    }
}


class Service1{
    //创建锁
    private ReentrantLock lock1 = new ReentrantLock();
    private ReentrantLock lock2 = new ReentrantLock();
    //创建通讯器
    private Condition condition = lock1.newCondition();
    //创建一个开关
    private boolean off = false;
    
    public void push(){
        try {
            lock1.lock();
            if(off == false) condition.wait();
            System.out.println("生产!");
            off = false;
            //让线程睡一会,保证B线程能够被锁住
            Thread.sleep(3000);
            this.pop();
            condition.signalAll();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock1.unlock();
        }
    }
    public void pop(){
        try {
            lock2.lock();
            if(off == true) condition.wait();
            System.out.println("消费!");
            off = true;
            Thread.sleep(3000);
            this.push();
            condition.signalAll();
        } catch (Exception e) {
            // TODO: handle exception
        }finally {
            lock2.unlock();
        }
    }
}