我最近在接受采访时提到了这个问题。
我回答说如果交错出错就会发生死锁,但是访谈者坚持认为无论交错都会写入总是陷入死锁的程序。
我们可以写这样的程序吗?你能指点我这样的示例程序吗?
答案 0 :(得分:95)
更新:This question was the subject of my blog in January 2013。谢谢你提出的好问题!
无论线程如何安排,我们如何编写一个永远陷入死锁的程序?
这是C#中的一个例子。请注意,程序似乎不包含锁和没有共享数据。它只有一个局部变量和三个语句,但它有100%的确定性死锁。 人们很难想出一个更加简单的程序,这个程序肯定会陷入僵局。
向读者练习#1:解释这种僵局。 (答案在评论中。)
向读者练习#2:在Java中演示相同的死锁。 (答案在这里:https://stackoverflow.com/a/9286697/88656)
class MyClass
{
static MyClass()
{
// Let's run the initialization on another thread!
var thread = new System.Threading.Thread(Initialize);
thread.Start();
thread.Join();
}
static void Initialize()
{ /* TODO: Add initialization code */ }
static void Main()
{ }
}
答案 1 :(得分:27)
此处的锁存器确保在每个线程试图锁定另一个锁时保持两个锁:
import java.util.concurrent.CountDownLatch;
public class Locker extends Thread {
private final CountDownLatch latch;
private final Object obj1;
private final Object obj2;
Locker(Object obj1, Object obj2, CountDownLatch latch) {
this.obj1 = obj1;
this.obj2 = obj2;
this.latch = latch;
}
@Override
public void run() {
synchronized (obj1) {
latch.countDown();
try {
latch.await();
} catch (InterruptedException e) {
throw new RuntimeException();
}
synchronized (obj2) {
System.out.println("Thread finished");
}
}
}
public static void main(String[] args) {
final Object obj1 = new Object();
final Object obj2 = new Object();
final CountDownLatch latch = new CountDownLatch(2);
new Locker(obj1, obj2, latch).start();
new Locker(obj2, obj1, latch).start();
}
}
有意运行jconsole,它会在Threads选项卡中正确显示死锁。
答案 2 :(得分:23)
Deadlock happens当线程(或任何平台调用其执行单元)获取资源时,每个资源一次只能由一个线程持有,并以这样的方式保留这些资源hold不能被抢占,并且线程之间存在一些“循环”关系,使得死锁中的每个线程都在等待获取另一个线程持有的某些资源。
因此,避免死锁的一种简单方法是为资源提供一些总排序,并强制规定资源只能由线程按顺序获取。相反,可以通过运行获取资源的线程有意地创建死锁,但不要按顺序获取它们。例如:
两个线程,两个锁。第一个线程运行一个循环,尝试以某种顺序获取锁,第二个线程运行一个循环,尝试以相反的顺序获取锁。成功获取锁后,每个线程都释放两个锁。
public class HighlyLikelyDeadlock {
static class Locker implements Runnable {
private Object first, second;
Locker(Object first, Object second) {
this.first = first;
this.second = second;
}
@Override
public void run() {
while (true) {
synchronized (first) {
synchronized (second) {
System.out.println(Thread.currentThread().getName());
}
}
}
}
}
public static void main(final String... args) {
Object lock1 = new Object(), lock2 = new Object();
new Thread(new Locker(lock1, lock2), "Thread 1").start();
new Thread(new Locker(lock2, lock1), "Thread 2").start();
}
}
现在,在这个问题中有一些评论指出了死锁的似然和确定性之间的区别。从某种意义上说,这种区别是一个学术问题。从实际的角度来看,我当然希望看到一个正在运行的系统,它与我上面编写的代码没有死锁:)
然而,面试问题有时可能是学术性的,这个问题确实在标题中有“肯定”这个词,所以接下来的是当然死锁的程序。创建了两个Locker
个对象,每个对象都有两个锁,一个CountDownLatch
用于在线程之间进行同步。每个Locker
锁定第一个锁,然后对锁存器进行一次倒计时。当两个线程都已获得锁定并向下计数锁存器时,它们继续经过锁存屏障并尝试获取第二个锁定,但在每种情况下,另一个线程已经保持所需的锁定。这种情况导致某种死锁。
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class CertainDeadlock {
static class Locker implements Runnable {
private CountDownLatch latch;
private Lock first, second;
Locker(CountDownLatch latch, Lock first, Lock second) {
this.latch = latch;
this.first = first;
this.second = second;
}
@Override
public void run() {
String threadName = Thread.currentThread().getName();
try {
first.lock();
latch.countDown();
System.out.println(threadName + ": locked first lock");
latch.await();
System.out.println(threadName + ": attempting to lock second lock");
second.lock();
System.out.println(threadName + ": never reached");
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
public static void main(final String... args) {
CountDownLatch latch = new CountDownLatch(2);
Lock lock1 = new ReentrantLock(), lock2 = new ReentrantLock();
new Thread(new Locker(latch, lock1, lock2), "Thread 1").start();
new Thread(new Locker(latch, lock2, lock1), "Thread 2").start();
}
}
答案 3 :(得分:12)
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
答案 4 :(得分:12)
以下是Eric Lippert的一个Java示例:
public class Lock implements Runnable {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public void run() {
try {
Thread t = new Thread(new Lock());
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
}
答案 5 :(得分:8)
我重写了Yuriy Zubarev的Java版本的死锁示例,由Eric Lippert发布:https://stackoverflow.com/a/9286697/2098232更接近C#版本。如果Java的初始化块与C#静态构造函数类似,并且首先获取锁,我们不需要另一个线程来调用join方法来获取死锁,它只需要从Lock类调用一些静态方法,就像原来的C#一样例。造成的死锁似乎证实了这一点。
public class Lock {
static {
System.out.println("Getting ready to greet the world");
try {
Thread t = new Thread(new Runnable(){
@Override
public void run() {
Lock.initialize();
}
});
t.start();
t.join();
} catch (InterruptedException ex) {
System.out.println("won't see me");
}
}
public static void main(String[] args) {
System.out.println("Hello World!");
}
public static void initialize(){
System.out.println("Initializing");
}
}
答案 6 :(得分:5)
这不是一个最简单的面试任务:在我的项目中,它使整个团队的工作陷入瘫痪状态。让你的程序停止是很容易的,但很难让它进入thread dump写的东西,
Found one Java-level deadlock:
=============================
"Thread-2":
waiting to lock monitor 7f91c5802b58 (object 7fb291380, a java.lang.String),
which is held by "Thread-1"
"Thread-1":
waiting to lock monitor 7f91c6075308 (object 7fb2914a0, a java.lang.String),
which is held by "Thread-2"
Java stack information for the threads listed above:
===================================================
"Thread-2":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb291380> (a java.lang.String)
- locked <7fb2914a0> (a java.lang.String)
- locked <7f32a0760> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)
"Thread-1":
at uk.ac.ebi.Deadlock.run(Deadlock.java:54)
- waiting to lock <7fb2914a0> (a java.lang.String)
- locked <7fb291380> (a java.lang.String)
- locked <7f32a0580> (a uk.ac.ebi.Deadlock)
at java.lang.Thread.run(Thread.java:680)
所以目标是获得JVM认为会陷入僵局的死锁。显然,没有像
这样的解决方案synchronized (this) {
wait();
}
将在这个意义上起作用,即使它们确实会永远停止。依靠竞争条件也不是一个好主意,因为在面试过程中你通常希望展示一些可以证明有效的东西,而不是大部分时间应该起作用的东西。
现在,sleep()
解决方案在某种意义上是可行的,很难想象它不起作用的情况,但不公平(我们在公平的运动中,不是吗?)。 The solution by @artbristol(我的是相同的,只是作为监视器的不同对象)很好,但很长并且使用新的并发原语来使线程处于正确的状态,这不是那么有趣:
public class Deadlock implements Runnable {
private final Object a;
private final Object b;
private final static CountDownLatch latch = new CountDownLatch(2);
public Deadlock(Object a, Object b) {
this.a = a;
this.b = b;
}
public synchronized static void main(String[] args) throws InterruptedException {
new Thread(new Deadlock("a", "b")).start();
new Thread(new Deadlock("b", "a")).start();
}
@Override
public void run() {
synchronized (a) {
latch.countDown();
try {
latch.await();
} catch (InterruptedException ignored) {
}
synchronized (b) {
}
}
}
}
我确实记得synchronized
- 仅解决方案适合11..13行代码(不包括注释和导入),但还没有回忆起实际的技巧。如果我这样做会更新。
更新:这是synchronized
上的一个丑陋的解决方案:
public class Deadlock implements Runnable {
public synchronized static void main(String[] args) throws InterruptedException {
synchronized ("a") {
new Thread(new Deadlock()).start();
"a".wait();
}
synchronized ("") {
}
}
@Override
public void run() {
synchronized ("") {
synchronized ("a") {
"a".notifyAll();
}
synchronized (Deadlock.class) {
}
}
}
}
注意我们用对象监视器替换一个锁存器(使用"a"
作为对象)。
答案 7 :(得分:4)
这个C#版本,我想java应该非常相似。
static void Main(string[] args)
{
var mainThread = Thread.CurrentThread;
mainThread.Join();
Console.WriteLine("Press Any key");
Console.ReadKey();
}
答案 8 :(得分:3)
import java.util.concurrent.CountDownLatch;
public class SO8880286 {
public static class BadRunnable implements Runnable {
private CountDownLatch latch;
public BadRunnable(CountDownLatch latch) {
this.latch = latch;
}
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " starting");
synchronized (BadRunnable.class) {
System.out.println("Thread " + Thread.currentThread().getId() + " acquired the monitor on BadRunnable.class");
latch.countDown();
while (true) {
try {
latch.await();
} catch (InterruptedException ex) {
continue;
}
break;
}
}
System.out.println("Thread " + Thread.currentThread().getId() + " released the monitor on BadRunnable.class");
System.out.println("Thread " + Thread.currentThread().getId() + " ending");
}
}
public static void main(String[] args) {
Thread[] threads = new Thread[2];
CountDownLatch latch = new CountDownLatch(threads.length);
for (int i = 0; i < threads.length; ++i) {
threads[i] = new Thread(new BadRunnable(latch));
threads[i].start();
}
}
}
程序总是死锁,因为每个线程都在屏障处等待其他线程,但为了等待屏障,线程必须将监视器放在BadRunnable.class
上。
答案 9 :(得分:2)
简单的搜索给了我以下代码:
public class Deadlock {
static class Friend {
private final String name;
public Friend(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public synchronized void bow(Friend bower) {
System.out.format("%s: %s"
+ " has bowed to me!%n",
this.name, bower.getName());
bower.bowBack(this);
}
public synchronized void bowBack(Friend bower) {
System.out.format("%s: %s"
+ " has bowed back to me!%n",
this.name, bower.getName());
}
}
public static void main(String[] args) {
final Friend alphonse =
new Friend("Alphonse");
final Friend gaston =
new Friend("Gaston");
new Thread(new Runnable() {
public void run() { alphonse.bow(gaston); }
}).start();
new Thread(new Runnable() {
public void run() { gaston.bow(alphonse); }
}).start();
}
}
来源:Deadlock
答案 10 :(得分:2)
这里有一个Java示例
http://baddotrobot.com/blog/2009/12/24/deadlock/
如果绑架者在获得现金之前拒绝放弃受害者而陷入僵局,但谈判者拒绝放弃现金,直到他找到受害者为止。
答案 11 :(得分:1)
这是一个示例,其中一个持有锁的线程启动另一个需要相同锁的线程,然后启动器等待直到开始完成...永远:
class OuterTask implements Runnable {
private final Object lock;
public OuterTask(Object lock) {
this.lock = lock;
}
public void run() {
System.out.println("Outer launched");
System.out.println("Obtaining lock");
synchronized (lock) {
Thread inner = new Thread(new InnerTask(lock), "inner");
inner.start();
try {
inner.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class InnerTask implements Runnable {
private final Object lock;
public InnerTask(Object lock) {
this.lock = lock;
}
public void run() {
System.out.println("Inner launched");
System.out.println("Obtaining lock");
synchronized (lock) {
System.out.println("Obtained");
}
}
}
class Sample {
public static void main(String[] args) throws InterruptedException {
final Object outerLock = new Object();
OuterTask outerTask = new OuterTask(outerLock);
Thread outer = new Thread(outerTask, "outer");
outer.start();
outer.join();
}
}
答案 12 :(得分:0)
以下是一个例子:
两个线程正在运行,每个线程都在等待其他线程释放锁定
公共类ThreadClass扩展了Thread {
String obj1,obj2;
ThreadClass(String obj1,String obj2){
this.obj1=obj1;
this.obj2=obj2;
start();
}
public void run(){
synchronized (obj1) {
System.out.println("lock on "+obj1+" acquired");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("waiting for "+obj2);
synchronized (obj2) {
System.out.println("lock on"+ obj2+" acquired");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
运行此操作会导致死锁:
公共类SureDeadlock {public static void main(String[] args) {
String obj1= new String("obj1");
String obj2= new String("obj2");
new ThreadClass(obj1,obj2);
new ThreadClass(obj2,obj1);
}
}