您的位置:首页 > 编程语言 > Java开发

java学习多线程之死锁

2013-10-20 16:09 429 查看
形成死锁的前提是同步代码块嵌套。

什么是死锁?当一个线程拿到锁以后在这个锁内部的代码需要访问另一段的代码的时候另外一个程序的锁被另外一个线程拿到,这样的话,就造成了两个锁互不想让程序没法往下执行的这种状况就是死锁。

class DeadDemoA implements Runnable
{
Object  obj = new Object();
int x = 0;

public void run()
{

if(x == 0){

while(true)
{

synchronized(obj)
{
System.out.println("-----");

showA();

System.out.println("-----");

}
showA();

}

}else{

while(true)
{
showA();
x = x+1;
x = x%2;
}

}

}

public synchronized void showA()
{

synchronized (obj)
{

System.out.println("SI suo");

}

}

}

class DeadLock
{

public static void main(String[] args) {

DeadDemoA a = new DeadDemoA();
Thread t1 = new Thread(a);
Thread t2 = new Thread(a);
Thread t3 = new Thread(a);
Thread t4 = new Thread(a);

t1.start();
t2.start();
t3.start();
t4.start();

}

}


以上就是一个死锁。

简单来说就是一段程序代码中有两个同步的代码块嵌套,也就是有两个锁,但是一个锁的执行依赖另外一个锁。

代码中A方法要调用B方法,同时这两个都是同步的,有各自的锁A比如说有A锁,B比如说有B锁,那么A方法要执行完成的话,必须同时具备A锁和B锁,如果此时B锁被其他线程拿到的话,这个时候A就等待B锁,同时其他线程也没法执行A方法,这个时候就是相互僵持,成为死锁。同时要注意,锁这个概念是针对线程的,跟本身的程序没有关系。我们再来写个死锁的示例:

class DDlock1 implements Runnable
{

private Object obj = new Object();

public void run()
{

while(true)
{
synchronized (obj)
{
show();

}
show();//let other thread get the lock
}

}

public synchronized void show()
{

synchronized(obj){

System.out.println("Dead lock example~");
}

}

}

class DeadLock1
{

public static void main(String[] args) {

DDlock1 d = new DDlock1();

Thread t1 = new Thread(d);
Thread t2 = new Thread(d);
Thread t3 = new Thread(d);
Thread t4 = new Thread(d);

t1.start();
t2.start();
t3.start();
t4.start();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: