在Java学习到线程这一部分的时候,都会遇到关于死锁的相关概念知识点,看了好多资料,上面有个经典的例子来说明什么是死锁,今天小编也拿来研究一下:
死锁的规范定义:集合中的每一个进程都在等待只能由本集合中的其他进程才能引发的事件,那么该组进程是死锁的。
一种情形,此时执行程序中两个或多个线程发生永久堵塞(等待),每个线程都在等待被
死锁
其他线程占用并堵塞了的资源。例如,如果线程A锁住了记录1并等待记录2,而线程B锁住了记录2并等待记录1,这样两个线程就发生了死锁现象。
题目:两个人就餐,但是只有一双筷子,A已经拿起了一只筷子,他只需要等待第二只筷子,但是这个时候B也拿起了一只筷子,也在等待另一只筷子,这时就是一个死锁状态,谁也吃不了饭。
具体代码如下:
public class ThreadBLock {
static String chopsticks1 = “筷子1”,chopsticks2 = “筷子2”;
static class A extends Thread{
public void run(){
synchronized(chopsticks1){ //synchronized关键字是用来对共享资源实行同步访问的,被该关键字修饰的代码,
// 在有线程开始执行时首先对其进行锁定,其他线程此时不能执行该段代码,知道当前线程执行完解除锁定
System.out.println(“A 拿起了 “+chopsticks1+”, 等待”+chopsticks2);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
synchronized(chopsticks2){
System.out.println(“A 又拿起了 “+chopsticks2);
}
}
}
}
static class B extends Thread{
public void run(){
synchronized(chopsticks2){
System.out.println(“B 拿起了 “+chopsticks2+”,等待 “+chopsticks1);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
synchronized(chopsticks1){
System.out.println(“B 又拿起了 “+chopsticks1);
}
}
}
}
}
然后写一个测试类来看看结果:
import cn.gjz.study.ThreadBLock.A;
import cn.gjz.study.ThreadBLock.B;
public class ThreadLockTest extends Thread {
public ThreadLockTest(){
this.setDaemon(true);
}
public void run(){
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
System.out.println(“守护线程,程序正在运行…”);
}
}
public static void main(String[] args){
new A().start();
new B().start();
new ThreadLockTest().start();
}
}
简单的小例子,有助于我们小白理解死锁的概念。大神请绕过!