0%

Java并发引入之优缺点

并发分为“进程并发”和“线程并发”,Java并发属于后者。

一、优点

  • 使能充分利用现代计算机的多CPU和多CPU核,提升并行/并发度,加快程序执行速度
  • 契合某些问题域模型,比如“生产者-消费者问题”

二、缺点

  • 需要耗费额外的资源,比如“线程创建”,“用于保存线程对象的内存”,“因上下文切换而消耗的CPU时间”等
  • 需要耗费更多精力用于编写正确可运行,线程安全的程序,需要考虑“可见性,有序性,原子性,死锁”等问题

以下是一份简单的会导致出现死锁的示例代码:

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
42
public class DeadLockDemo {
private static String A = "A";
private static String B = "B";

public static void main(String[] args) {
new DeadLockDemo().deadLock();
}

private void deadLock() {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (A) {
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}

synchronized (B) {
System.out.println("1");
}
}
}
});

Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (B) {
synchronized (A) {
System.out.println("2");
}
}
}
});

t1.start();
t2.start();
}

}

执行该Java程序,通过jstack命令查看线程栈,以下是呈现死锁状态的线程栈相关内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
"Thread-1" #9 prio=5 os_prio=0 tid=0x00007f34d80cd000 nid=0x513c waiting for monitor entry [0x00007f34dcb69000]
java.lang.Thread.State: BLOCKED (on object monitor)
at DeadLockDemo$2.run(DeadLockDemo.java:33)
- waiting to lock <0x00000000b2e5a7e8> (a java.lang.String)
- locked <0x00000000b2e5a818> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)

"Thread-0" #8 prio=5 os_prio=0 tid=0x00007f34d80cb800 nid=0x513b waiting for monitor entry [0x00007f34dcc6a000]
java.lang.Thread.State: BLOCKED (on object monitor)
at DeadLockDemo$1.run(DeadLockDemo.java:21)
- waiting to lock <0x00000000b2e5a818> (a java.lang.String)
- locked <0x00000000b2e5a7e8> (a java.lang.String)
at java.lang.Thread.run(Thread.java:748)
您的支持将鼓励我继续分享!