Java并发编程是Java企业级开发中的重要组成部分,本文将深入探讨Java并发编程的核心概念和实践技巧。
线程基础
创建线程
Java提供了两种创建线程的基本方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 方式1:继承Thread类
public class MyThread extends Thread {
@Override
public void run () {
System . out . println ( "Thread is running" );
}
}
// 方式2:实现Runnable接口
public class MyRunnable implements Runnable {
@Override
public void run () {
System . out . println ( "Runnable is running" );
}
}
线程同步
synchronized关键字
1
2
3
4
5
6
7
8
9
10
11
public class Counter {
private int count = 0 ;
public synchronized void increment () {
count ++ ;
}
public synchronized int getCount () {
return count ;
}
}
Lock接口
1
2
3
4
5
6
7
8
9
10
11
12
13
public class Counter {
private final Lock lock = new ReentrantLock ();
private int count = 0 ;
public void increment () {
lock . lock ();
try {
count ++ ;
} finally {
lock . unlock ();
}
}
}
线程通信
wait/notify机制
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Buffer {
private Queue < String > queue = new LinkedList <> ();
private int capacity = 10 ;
public synchronized void put ( String item ) throws InterruptedException {
while ( queue . size () == capacity ) {
wait ();
}
queue . add ( item );
notify ();
}
public synchronized String take () throws InterruptedException {
while ( queue . isEmpty ()) {
wait ();
}
String item = queue . remove ();
notify ();
return item ;
}
}
线程池
ExecutorService的使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class ThreadPoolExample {
public static void main ( String [] args ) {
ExecutorService executor = Executors . newFixedThreadPool ( 5 );
for ( int i = 0 ; i < 10 ; i ++ ) {
final int taskId = i ;
executor . submit (() -> {
System . out . println ( "Task " + taskId + " is running on " +
Thread . currentThread (). getName ());
});
}
executor . shutdown ();
}
}
自定义线程池
1
2
3
4
5
6
7
ThreadPoolExecutor executor = new ThreadPoolExecutor (
5 , // 核心线程数
10 , // 最大线程数
60L , // 空闲线程存活时间
TimeUnit . SECONDS , // 时间单位
new ArrayBlockingQueue <> ( 100 ) // 工作队列
);
并发集合
ConcurrentHashMap的使用
1
2
3
4
5
6
7
8
9
10
11
12
public class ConcurrentMapExample {
private ConcurrentHashMap < String , Integer > map = new ConcurrentHashMap <> ();
public void processData ( String key ) {
map . computeIfAbsent ( key , k -> calculateValue ( k ));
}
private Integer calculateValue ( String key ) {
// 复杂计算
return key . length ();
}
}
原子操作
Atomic类的使用
1
2
3
4
5
6
7
8
9
10
11
public class AtomicCounter {
private AtomicInteger count = new AtomicInteger ( 0 );
public void increment () {
count . incrementAndGet ();
}
public int getCount () {
return count . get ();
}
}
并发工具类
CountDownLatch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class ServiceStarter {
public void startServices () {
int serviceCount = 3 ;
CountDownLatch latch = new CountDownLatch ( serviceCount );
new Thread (() -> {
startDatabase ();
latch . countDown ();
}). start ();
new Thread (() -> {
startCache ();
latch . countDown ();
}). start ();
new Thread (() -> {
startWebServer ();
latch . countDown ();
}). start ();
latch . await (); // 等待所有服务启动
System . out . println ( "All services started" );
}
}
CyclicBarrier
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class DataProcessor {
private final CyclicBarrier barrier ;
public DataProcessor ( int parties ) {
this . barrier = new CyclicBarrier ( parties , () -> {
System . out . println ( "All parties have completed phase" );
});
}
public void processData () {
try {
// 第一阶段
doPhaseOne ();
barrier . await ();
// 第二阶段
doPhaseTwo ();
barrier . await ();
} catch ( Exception e ) {
Thread . currentThread (). interrupt ();
}
}
}
最佳实践
合理使用线程池
避免过度同步
正确处理中断
使用并发集合
遵循线程安全设计原则
性能优化
减少锁的粒度
使用读写锁分离
避免死锁
合理设置线程池参数
常见问题
死锁预防
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class DeadlockPrevention {
private final Object lock1 = new Object ();
private final Object lock2 = new Object ();
public void method1 () {
synchronized ( lock1 ) {
synchronized ( lock2 ) {
// 业务逻辑
}
}
}
public void method2 () {
synchronized ( lock1 ) { // 保持一致的锁定顺序
synchronized ( lock2 ) {
// 业务逻辑
}
}
}
}
总结
Java并发编程是一个复杂但重要的主题,掌握好这些核心概念和工具,可以帮助我们构建高效、可靠的并发应用。
参考资料
Java并发编程实战
Java并发编程的艺术
Doug Lea的并发编程著作
Licensed under CC BY-NC-SA 4.0