java如何实现线程
线程的实现方式
在Java中,线程可以通过继承Thread类或实现Runnable接口来实现。两种方式各有优缺点,具体选择取决于需求。
继承Thread类
通过继承Thread类并重写run()方法,可以创建一个线程类。启动线程时调用start()方法。
class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
实现Runnable接口
实现Runnable接口并重写run()方法,然后将实例传递给Thread类的构造函数。这种方式更灵活,因为Java不支持多重继承。
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running");
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
线程的生命周期
线程的生命周期包括新建(New)、就绪(Runnable)、运行(Running)、阻塞(Blocked)和终止(Terminated)五个状态。
- 新建状态:线程对象被创建但未调用
start()方法。 - 就绪状态:调用
start()方法后,线程等待CPU分配资源。 - 运行状态:线程获得CPU资源,执行
run()方法。 - 阻塞状态:线程因等待I/O操作、锁或其他资源而暂停执行。
- 终止状态:线程执行完毕或异常退出。
线程的常用方法
- start():启动线程,进入就绪状态。
- run():线程执行的主体方法。
- sleep(long millis):使线程休眠指定毫秒数。
- join():等待线程终止。
- interrupt():中断线程。
- isAlive():检查线程是否存活。
线程同步
多线程环境下,共享资源的访问可能导致数据不一致。Java提供了synchronized关键字和Lock接口实现线程同步。
synchronized关键字
synchronized可以修饰方法或代码块,确保同一时间只有一个线程访问共享资源。
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
}
Lock接口
Lock接口提供了更灵活的锁机制,如ReentrantLock。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private Lock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
}
线程池
线程池可以有效管理线程资源,避免频繁创建和销毁线程的开销。Java提供了ExecutorService框架实现线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
Runnable worker = new MyRunnable();
executor.execute(worker);
}
executor.shutdown();
}
}
线程间通信
线程间可以通过wait()、notify()和notifyAll()方法实现通信。这些方法必须在synchronized块或方法中调用。
class SharedResource {
private boolean flag = false;
public synchronized void produce() {
while (flag) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
flag = true;
notify();
}
public synchronized void consume() {
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
flag = false;
notify();
}
}
线程安全集合
Java提供了线程安全的集合类,如ConcurrentHashMap、CopyOnWriteArrayList等,可以在多线程环境下安全使用。
import java.util.concurrent.ConcurrentHashMap;
public class Main {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("key", 1);
System.out.println(map.get("key"));
}
}
线程的注意事项
- 避免过度使用线程,合理控制线程数量。
- 注意线程安全问题,合理使用同步机制。
- 避免死锁,确保锁的获取和释放顺序一致。
- 使用线程池管理线程资源,提高性能。







