在当今多核处理器普及的时代,Java 并发编程已成为构建高性能、可伸缩应用程序的关键技能。作为一名 Java 高级工程师,深入掌握并发编程不仅能提升应用性能,还能更好地应对复杂业务场景。本文将从基础概念入手,逐步深入到实际应用中的优化技巧,并辅以相关代码示例。
一、Java 并发基础概念
线程与进程
进程是程序的一次执行过程,是系统进行资源分配和调度的基本单位,每个进程都有独立的内存空间。而线程是进程中的一个执行单元,是 CPU 调度和分派的基本单位,多个线程共享进程的内存空间。在 Java 中,创建线程主要有两种方式:继承 Thread
类和实现 Runnable
接口。
示例代码:继承 Thread 类
收起
java
class MyThread extends Thread {@Overridepublic void run() {System.out.println("This is a thread created by extending Thread class.");}
}public class ThreadExample {public static void main(String[] args) {MyThread myThread = new MyThread();myThread.start();}
}
示例代码:实现 Runnable 接口
收起
java
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("This is a thread created by implementing Runnable interface.");}
}public class RunnableExample {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();Thread thread = new Thread(myRunnable);thread.start();}
}
线程安全问题
当多个线程同时访问共享资源时,如果处理不当,就会出现线程安全问题。例如,多个线程同时对一个共享变量进行读写操作,可能导致数据不一致。
示例代码:线程安全问题演示
收起
java
public class UnsafeCounter {private int count = 0;public void increment() {count++;}public int getCount() {return count;}
}public class ThreadSafetyProblem {public static void main(String[] args) {UnsafeCounter counter = new UnsafeCounter();Thread[] threads = new Thread[1000];for (int i = 0; i < 1000; i++) {threads[i] = new Thread(() -> {for (int j = 0; j < 1000; j++) {counter.increment();}});threads[i].start();}for (Thread thread : threads) {try {thread.join();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("Expected count: 1000000, Actual count: " + counter.getCount());}
}
在上述代码中,UnsafeCounter
类的 increment
方法不是线程安全的,因为 count++
操作实际上包含