java使用lock实现一个简单的死锁程序
Posted 沙和尚-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java使用lock实现一个简单的死锁程序相关的知识,希望对你有一定的参考价值。
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(); } } }
以上是关于java使用lock实现一个简单的死锁程序的主要内容,如果未能解决你的问题,请参考以下文章