多线程是 Java 编程中非常重要的一个知识点,它可以让程序同时执行多个任务,从而提高程序的效率和响应速度。对于初学者来说,理解多线程并不是很难,只要掌握几个核心概念和常用方法,再结合实战案例,就能快速上手。本文将从基础概念、实现方式、注意事项到实战案例一步步讲解,保证你跟着敲一次代码就能掌握。
NEW:新建状态,线程对象刚创建,还没有调用 start()。RUNNABLE:可运行状态,线程已经调用 start(),等待 CPU 调度。RUNNING:运行状态,线程正在执行代码。BLOCKED/WATING/TIMED_WAITING:阻塞/等待状态。TERMINATED:终止状态,线程执行完毕。Thread 类// 定义一个线程类
class MyThread extends Thread {
@Override
public void run() {
// 线程要执行的任务
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " 正在运行: " + i);
try {
Thread.sleep(500); // 暂停 0.5 秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
t1.start(); // 启动线程
t2.start();
}
}
注意点:
run() 方法中写线程执行的逻辑,不能直接调用 run() 来启动线程,要用 start()。Thread.sleep() 可以让线程休眠,单位是毫秒。start(),重复调用会报异常。Runnable 接口class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " 正在运行: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ThreadDemo2 {
public static void main(String[] args) {
Thread t1 = new Thread(new MyRunnable());
Thread t2 = new Thread(new MyRunnable());
t1.start();
t2.start();
}
}
优势:
| 方法 | 功能 |
|---|---|
start() |
启动线程,调用run()方法 |
run() |
线程执行的入口方法 |
sleep(ms) |
线程休眠,单位毫秒 |
join() |
等待线程执行完成再继续 |
setName()/getName() |
设置或获取线程名字 |
currentThread() |
获取当前执行线程对象 |
示例:使用 join()
public class JoinDemo {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 1; i <= 3; i++) {
System.out.println("子线程: " + i);
}
});
t1.start();
t1.join(); // 等待 t1 执行完
System.out.println("主线程继续执行");
}
}
多线程同时操作共享资源时,会出现 线程安全问题。最常见的情况是多个线程同时修改一个变量,可能导致结果不正确。
class Counter {
private int count = 0;
// 不安全的加法
public void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class ThreadSafeDemo {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("最终结果: " + counter.getCount()); // 可能不是 2000
}
}
解决方法:使用 synchronized
class SafeCounter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
假设我们要同时下载 3 个文件,可以用多线程模拟:
class DownloadTask implements Runnable {
private String fileName;
public DownloadTask(String fileName) {
this.fileName = fileName;
}
@Override
public void run() {
System.out.println(fileName + " 开始下载");
try {
Thread.sleep((long) (Math.random() * 2000)); // 模拟下载时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(fileName + " 下载完成");
}
}
public class DownloadDemo {
public static void main(String[] args) {
String[] files = {"文件1", "文件2", "文件3"};
for (String file : files) {
new Thread(new DownloadTask(file)).start();
}
}
}
效果:
run() 方法,要用 start()。synchronized 或 Lock。Executors),避免手动创建过多线程。通过本文的讲解,你已经掌握了以下知识点:
Thread 和实现 Runnablestart()、sleep()、join()synchronized只要跟着敲一次代码,你就能理解多线程的基本用法,初步具备编写多线程程序的能力。



