How-to-understand-the-DeadLock

如何理解如下代码会造成DeadLock

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 10:36 2018/4/14.
*/
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 friend){
System.out.format("%s:%s" + " has bowed to me!%n", this.name, friend.getName());
friend.bowBack(this);
}
public synchronized void bowBack(Friend friend){
System.out.format("%s:%s" + " has bowed back to me!%n", this.name, friend.getName());
}
}

public static void main(String[] args) throws InterruptedException {
final Friend friendA = new Friend("Shuai");
final Friend friendB = new Friend("Junlan");
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2,
2, 1000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(2));
/// Why not using this way to create ThreadPool?
// ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
threadPoolExecutor.execute(() -> friendA.bow(friendB));
threadPoolExecutor.execute(() -> friendB.bow(friendA));
threadPoolExecutor.shutdown();

}
}

output

1
2
Shuai:Junlan has bowed to me!
Junlan:Shuai has bowed to me!

Conclusion

  • 类的实例对类中所有的synchronized方法都持有锁;(表述不够官方)

Java创建线程的三种方式(Thread/Runnable/Callable)

1.继承Thread类

此方式只需要重写Thread类中的run()方法即可,示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @author Junlan Shuai[shuaijunlan@gmail.com].
* @date Created on 19:41 2017/4/10.
*/
public class ExtendThread extends Thread
{
String name;
public ExtendThread(String name)
{
this.name = name;
}
@Override
public void run()
{
System.out.println(name);
}
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×