java如何使用多线程
多线程的基本概念
Java多线程允许程序同时执行多个任务,提高资源利用率和程序效率。线程是轻量级的进程,共享同一进程的资源。
创建线程的方法
继承Thread类
通过继承Thread类并重写run()方法实现多线程。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread running by extending Thread class");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
实现Runnable接口
更推荐的方式是实现Runnable接口,避免单继承的限制。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread running by implementing Runnable");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
使用Lambda表达式(Java 8+)
简化代码,直接通过Lambda表达式实现Runnable接口。
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
System.out.println("Thread running via Lambda");
});
thread.start();
}
}
线程池管理
使用ExecutorService管理线程池,避免频繁创建和销毁线程的开销。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
executor.execute(() -> {
System.out.println("Task executed by thread pool");
});
}
executor.shutdown(); // 关闭线程池
}
}
线程同步与锁
多线程共享资源时需同步,避免竞态条件。
synchronized关键字
通过synchronized修饰方法或代码块实现同步。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
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("Count: " + counter.getCount());
}
}
ReentrantLockReentrantLock提供更灵活的锁机制。
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程间通信
通过wait()、notify()和notifyAll()实现线程协作。
class SharedResource {
private boolean ready = false;
public synchronized void produce() {
ready = true;
notify(); // 通知等待的线程
}
public synchronized void consume() throws InterruptedException {
while (!ready) {
wait(); // 等待条件满足
}
System.out.println("Resource consumed");
}
}
线程状态与生命周期
线程状态包括NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING和TERMINATED。可通过Thread.getState()获取当前状态。

注意事项
- 避免死锁:确保锁的获取和释放顺序一致。
- 减少锁粒度:缩小同步块范围以提高性能。
- 使用线程安全集合:如
ConcurrentHashMap、CopyOnWriteArrayList等。






