Java线程相关对象全面解析与最佳实践
- Java线程相关对象全面解析与最佳实践
- 一、线程核心对象关系图
- 二、基础线程对象
- 1. Thread类 - 线程创建与控制
- 2. Callable与Future - 带返回值的线程
- 三、线程池框架
- 1. Executor框架核心组件
- 2. ThreadPoolExecutor高级配置
- 四、同步与锁机制
- 1. synchronized关键字
- 2. Lock框架
- 五、线程安全容器
- 六、原子操作类
- 七、线程局部变量
- 八、最佳实践总结
- 1. 线程创建选择
- 2. 同步机制选择
- 3. 线程安全容器选择
- 4. 内存模型与可见性
Java线程相关对象全面解析与最佳实践
一、线程核心对象关系图
二、基础线程对象
1. Thread类 - 线程创建与控制
class MyThread extends Thread {@Overridepublic void run() {System.out.println("线程执行: " + Thread.currentThread().getName());}
}
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("Runnable执行: " + Thread.currentThread().getName());}
}
public class ThreadExample {public static void main(String[] args) {MyThread thread1 = new MyThread();thread1.start();Thread thread2 = new Thread(new MyRunnable());thread2.start();Thread thread3 = new Thread(() -> {System.out.println("Lambda线程: " + Thread.currentThread().getName());});thread3.start();thread1.setPriority(Thread.MAX_PRIORITY); thread2.setDaemon(true); thread3.interrupt(); }
}
2. Callable与Future - 带返回值的线程
import java.util.concurrent.*;class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {Thread.sleep(1000);return "Callable执行结果";}
}public class CallableExample {public static void main(String[] args) throws Exception {ExecutorService executor = Executors.newSingleThreadExecutor();Future<String> future = executor.submit(new MyCallable());String result = future.get();System.out.println("结果: " + result);System.out.println("是否完成: " + future.isDone());System.out.println("是否取消: " + future.isCancelled());executor.shutdown();}
}
三、线程池框架
1. Executor框架核心组件
public class ExecutorFrameworkExample {public static void main(String[] args) {ExecutorService fixedPool = Executors.newFixedThreadPool(5);ExecutorService cachedPool = Executors.newCachedThreadPool();ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();ScheduledExecutorService scheduledPool = Executors.newScheduledThreadPool(3);for (int i = 0; i < 10; i++) {fixedPool.execute(() -> {System.out.println("任务执行: " + Thread.currentThread().getName());});}scheduledPool.scheduleAtFixedRate(() -> {System.out.println("定时任务执行");}, 1, 5, TimeUnit.SECONDS); fixedPool.shutdown();try {if (!fixedPool.awaitTermination(60, TimeUnit.SECONDS)) {fixedPool.shutdownNow();}} catch (InterruptedException e) {fixedPool.shutdownNow();}}
}
2. ThreadPoolExecutor高级配置
public class AdvancedThreadPool {public static void main(String[] args) {ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 20, 60L, TimeUnit.SECONDS,new ArrayBlockingQueue<>(100), new CustomThreadFactory(), new CustomRejectionPolicy() );ScheduledExecutorService monitor = Executors.newScheduledThreadPool(1);monitor.scheduleAtFixedRate(() -> {System.out.println("活跃线程: " + executor.getActiveCount());System.out.println("队列大小: " + executor.getQueue().size());System.out.println("完成任务: " + executor.getCompletedTaskCount());}, 0, 5, TimeUnit.SECONDS);}
}
class CustomThreadFactory implements ThreadFactory {private final AtomicInteger count = new AtomicInteger(1);@Overridepublic Thread newThread(Runnable r) {Thread thread = new Thread(r);thread.setName("custom-thread-" + count.getAndIncrement());thread.setPriority(Thread.NORM_PRIORITY);thread.setUncaughtExceptionHandler((t, e) -> {System.err.println("线程异常: " + t.getName() + ", 错误: " + e.getMessage());});return thread;}
}
class CustomRejectionPolicy implements RejectedExecutionHandler {@Overridepublic void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {System.err.println("任务被拒绝: " + r.toString());}
}
四、同步与锁机制
1. synchronized关键字
public class SynchronizedExample {private int count = 0;private final Object lock = new Object();public synchronized void increment() {count++;}public static synchronized void staticMethod() {}public void performTask() {synchronized (lock) {count++;}}private static volatile Singleton instance;public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}
2. Lock框架
import java.util.concurrent.locks.*;public class LockExample {private final ReentrantLock lock = new ReentrantLock();private final ReadWriteLock rwLock = new ReentrantReadWriteLock();private final Condition condition = lock.newCondition();private int sharedResource = 0;public void useReentrantLock() {lock.lock();try {sharedResource++;} finally {lock.unlock();}}public void useReadWriteLock() {rwLock.readLock().lock();try {System.out.println("读取资源: " + sharedResource);} finally {rwLock.readLock().unlock();}rwLock.writeLock().lock();try {sharedResource++;} finally {rwLock.writeLock().unlock();}}public void useCondition() throws InterruptedException {lock.lock();try {while (sharedResource == 0) {condition.await(); }sharedResource--;condition.signalAll(); } finally {lock.unlock();}}
}
五、线程安全容器
1. Concurrent集合类
public class ConcurrentCollectionExample {public static void main(String[] args) {ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();map.put("key1", 1);map.putIfAbsent("key1", 2); CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();list.add("item1");list.addIfAbsent("item1"); BlockingQueue<String> queue = new LinkedBlockingQueue<>(10);new Thread(() -> {try {for (int i = 0; i < 100; i++) {queue.put("item" + i);Thread.sleep(100);}} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();new Thread(() -> {try {while (true) {String item = queue.take();System.out.println("消费: " + item);}} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();}
}
2. 并发工具类
public class ConcurrentUtilsExample {public static void main(String[] args) throws InterruptedException {CountDownLatch latch = new CountDownLatch(3);for (int i = 0; i < 3; i++) {new Thread(() -> {try {Thread.sleep(1000);System.out.println("任务完成");latch.countDown();} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();}latch.await(); System.out.println("所有任务已完成");CyclicBarrier barrier = new CyclicBarrier(3, () -> {System.out.println("所有线程到达屏障点");});for (int i = 0; i < 3; i++) {new Thread(() -> {try {System.out.println("线程到达屏障");barrier.await();System.out.println("线程继续执行");} catch (Exception e) {e.printStackTrace();}}).start();}Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 10; i++) {new Thread(() -> {try {semaphore.acquire();System.out.println("线程获取许可,剩余许可: " + semaphore.availablePermits());Thread.sleep(1000);semaphore.release();} catch (InterruptedException e) {Thread.currentThread().interrupt();}}).start();}}
}
六、原子操作类
1. Atomic包使用
import java.util.concurrent.atomic.*;public class AtomicExample {private final AtomicInteger atomicInt = new AtomicInteger(0);private final AtomicReference<String> atomicRef = new AtomicReference<>("初始值");private final AtomicStampedReference<Integer> atomicStamped = new AtomicStampedReference<>(0, 0);public void useAtomicInteger() {atomicInt.set(10);int value = atomicInt.get();atomicInt.incrementAndGet(); atomicInt.getAndIncrement(); atomicInt.addAndGet(5); atomicInt.compareAndSet(10, 20); }public void useAtomicReference() {atomicRef.set("新值");String oldValue = atomicRef.getAndSet("更新值");boolean success = atomicRef.compareAndSet("期望值", "新值");}public void useAtomicStampedReference() {int[] stampHolder = new int[1];int currentStamp = atomicStamped.getStamp();Integer currentRef = atomicStamped.get(stampHolder);boolean success = atomicStamped.compareAndSet(currentRef, currentRef + 10, currentStamp, currentStamp + 1);}public class Counter {private final AtomicLong count = new AtomicLong(0);public void increment() {count.incrementAndGet();}public long getCount() {return count.get();}}
}
七、线程局部变量
1. ThreadLocal使用
public class ThreadLocalExample {private static final ThreadLocal<Integer> threadLocal = new ThreadLocal<>();private static final ThreadLocal<Integer> threadLocalWithInitial = ThreadLocal.withInitial(() -> 0);private static final InheritableThreadLocal<String> inheritableThreadLocal = new InheritableThreadLocal<>();public static void main(String[] args) {threadLocal.set(100);threadLocalWithInitial.set(200);inheritableThreadLocal.set("父线程值");System.out.println("线程局部值: " + threadLocal.get());System.out.println("初始线程局部值: " + threadLocalWithInitial.get());Thread childThread = new Thread(() -> {System.out.println("子线程继承值: " + inheritableThreadLocal.get());inheritableThreadLocal.set("子线程修改值");System.out.println("子线程新值: " + inheritableThreadLocal.get());});childThread.start();try {childThread.join();} catch (InterruptedException e) {Thread.currentThread().interrupt();}System.out.println("父线程最终值: " + inheritableThreadLocal.get());threadLocal.remove();threadLocalWithInitial.remove();inheritableThreadLocal.remove();}
}
八、最佳实践总结
1. 线程创建选择
场景 | 推荐方式 | 理由 |
---|
简单任务 | Runnable + Thread | 简单直接 |
需要返回值 | Callable + Future | 支持返回值 |
线程池任务 | ExecutorService | 资源管理 |
定时任务 | ScheduledExecutorService | 调度支持 |
2. 同步机制选择
场景 | 推荐机制 | 理由 |
---|
简单同步 | synchronized | 语法简单 |
复杂同步 | ReentrantLock | 功能丰富 |
读写分离 | ReadWriteLock | 性能优化 |
条件等待 | Condition | 精确控制 |
3. 线程安全容器选择
场景 | 推荐容器 | 理由 |
---|
并发映射 | ConcurrentHashMap | 高并发性能 |
并发列表 | CopyOnWriteArrayList | 读多写少 |
生产者消费者 | BlockingQueue | 线程安全队列 |
计数器 | AtomicLong | 无锁高性能 |
4. 内存模型与可见性
public class VisibilityExample {private volatile boolean running = true;private final AtomicInteger count = new AtomicInteger(0);public void start() {new Thread(() -> {while (running) { count.incrementAndGet();}}).start();}public void stop() {running = false; }
}
通过深入理解这些线程相关对象及其用法,您可以构建高效、安全的多线程应用程序。关键是根据具体场景选择合适的线程机制,并遵循最佳实践来避免常见的并发问题。