架构师老王:“因为并发编程需要处理多个线程同时访问共享资源的问题!主要挑战包括:线程安全、死锁、性能优化等。但掌握了核心原理,就能写出高效的并发程序。”
Java并发编程体系
|
+-----------------+-----------------+
| | |
线程基础 同步机制 并发工具类
| | |
Thread/Runnable synchronized 线程池/Lock
线程状态机 volatile CountDownLatch
ThreadLocal AQS原理 ConcurrentHashMap
/**
* 线程创建的多种方式
*/
public class ThreadCreationDemo {
// 方式1:继承Thread类
static class MyThread extends Thread {
private String threadName;
public MyThread(String name) {
this.threadName = name;
}
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " - Count: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
}
}
}
// 方式2:实现Runnable接口
static class MyRunnable implements Runnable {
private String taskName;
public MyRunnable(String name) {
this.taskName = name;
}
@Override
public void run() {
System.out.println("Task " + taskName + " is running on " +
Thread.currentThread().getName());
}
}
// 方式3:使用Callable和Future
static class MyCallable implements Callable<String> {
private String taskName;
public MyCallable(String name) {
this.taskName = name;
}
@Override
public String call() throws Exception {
Thread.sleep(2000);
return "Task " + taskName + " completed";
}
}
public static void main(String[] args) throws Exception {
// 创建和启动Thread
MyThread thread1 = new MyThread("Thread-1");
thread1.start();
// 使用Runnable
Thread thread2 = new Thread(new MyRunnable("Task-1"));
thread2.start();
// 使用Callable
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable("Callable-Task"));
System.out.println("Result: " + future.get());
executor.shutdown();
}
}
/**
* 线程状态演示
*/
public class ThreadStateDemo {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
try {
// RUNNABLE状态
System.out.println("Thread is running...");
// TIMED_WAITING状态
Thread.sleep(2000);
// BLOCKED状态 - 等待获取锁
synchronized (ThreadStateDemo.class) {
System.out.println("Thread got the lock");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
System.out.println("1. Initial state: " + thread.getState()); // NEW
thread.start();
System.out.println("2. After start: " + thread.getState()); // RUNNABLE
Thread.sleep(500);
System.out.println("3. During sleep: " + thread.getState()); // TIMED_WAITING
thread.join();
System.out.println("4. After completion: " + thread.getState()); // TERMINATED
}
}
/**
* synchronized的多种使用方式
*/
public class SynchronizedDemo {
private int count = 0;
private static int staticCount = 0;
private final Object lock = new Object();
// 1. 同步实例方法
public synchronized void incrementInstance() {
count++;
System.out.println("Instance count: " + count);
}
// 2. 同步静态方法
public static synchronized void incrementStatic() {
staticCount++;
System.out.println("Static count: " + staticCount);
}
// 3. 同步代码块 - 对象锁
public void incrementWithBlock() {
synchronized (this) {
count++;
System.out.println("Block count: " + count);
}
}
// 4. 同步代码块 - 自定义锁
public void incrementWithCustomLock() {
synchronized (lock) {
count++;
System.out.println("Custom lock count: " + count)