安装JDK
sudo yum install java-1.8.0-openjdk-devel # 安装JDK 8(推荐)
java -version # 验证安装
开发工具
继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程执行:" + Thread.currentThread().getName());
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Callable和Future(带返回值)
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
@Override
public Integer call() {
return 42;
}
}
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
System.out.println("结果:" + future.get());
executor.shutdown();
}
}
线程状态
start()后等待CPU调度。run()方法。wait()暂停。线程同步
synchronized (lock) {
// 临界区代码
}
ReentrantLock)。Lock lock = new ReentrantLock();
lock.lock();
try {
// 临界区代码
} finally {
lock.unlock();
}
线程池
ExecutorService管理线程,避免频繁创建/销毁线程。ExecutorService executor = Executors.newFixedThreadPool(5); // 固定大小线程池
executor.submit(() -> System.out.println("任务执行"));
executor.shutdown();
死锁
jstack或VisualVM分析线程状态。性能优化
ReentrantReadWriteLock)提升并发读性能。Thread.sleep()滥用,优先使用wait/notify或Condition。线程安全集合
ConcurrentHashMap、CopyOnWriteArrayList等线程安全类,替代非线程安全的HashMap、ArrayList。System.out.println或日志框架(如Log4j)跟踪线程执行流程。jstack:查看线程堆栈信息,定位死锁或阻塞问题。VisualVM:监控线程状态、CPU和内存使用情况。CountDownLatch:等待多个线程完成任务。Semaphore:控制同时访问资源的线程数量。参考资料: