java线程如何使用
线程的基本概念
在Java中,线程是程序执行的最小单元,多线程允许程序同时执行多个任务。Java通过Thread类和Runnable接口提供线程支持。
创建线程的两种方式
继承Thread类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中");
}
}
// 使用方式
MyThread thread = new MyThread();
thread.start();
实现Runnable接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中");
}
}
// 使用方式
Thread thread = new Thread(new MyRunnable());
thread.start();
线程的生命周期
- 新建(New):线程对象创建后但未调用
start()。 - 就绪(Runnable):调用
start()后,等待CPU调度。 - 运行(Running):线程获取CPU资源执行
run()方法。 - 阻塞(Blocked):线程因等待资源或I/O操作暂停。
- 终止(Terminated):
run()方法执行完毕或异常退出。
线程常用方法
start():启动线程。run():定义线程执行的任务。sleep(long millis):暂停线程指定毫秒。join():等待线程终止。interrupt():中断线程。isAlive():检查线程是否存活。
线程同步与锁
多线程共享资源时需同步以避免竞态条件。
synchronized关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
ReentrantLock
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private final ReentrantLock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程池的使用
Java提供ExecutorService管理线程池,避免频繁创建销毁线程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.submit(() -> {
System.out.println("任务执行");
});
executor.shutdown();
线程间通信
通过wait()、notify()和notifyAll()实现。
class SharedResource {
private boolean flag = false;
public synchronized void waitForFlag() throws InterruptedException {
while (!flag) {
wait();
}
}
public synchronized void setFlag() {
flag = true;
notifyAll();
}
}
注意事项
- 避免死锁:确保锁的获取顺序一致。
- 减少锁粒度:仅同步必要代码块。
- 使用线程安全类:如
ConcurrentHashMap。 - 避免长时间占用锁:防止其他线程长时间等待。







