Java 中的多线程是通过并发编程来提高应用程序的效率和响应速度。Java 提供了多个机制和类来支持多线程编程,包括继承 Thread
类、实现 Runnable
接口、使用线程池等。以下是 Java 中一些常见的多线程操作和应用场景。
1. 创建线程
1.1 通过继承 Thread
类创建线程
继承 Thread
类并重写 run
方法是创建线程的一种方式。run
方法包含线程的执行体。
public class MyThread extends Thread {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // 启动线程
}
}
start()
方法会启动线程并调用run()
方法。run()
方法不能直接调用,必须通过start()
启动线程。
1.2 通过实现 Runnable
接口创建线程
Runnable
接口适合当你不想继承 Thread
类时使用。你只需要实现 run
方法,然后将其传递给 Thread
对象。
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("Thread is running: " + Thread.currentThread().getName());
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
}
}
2. 线程的生命周期
线程有几个常见的生命周期状态:
- 新建(New):线程对象被创建,但未调用
start()
方法。 - 可运行(Runnable):线程被启动,处于可运行状态,但可能被操作系统调度暂停。
- 阻塞(Blocked):线程正在等待某个资源。
- 等待(Waiting):线程正在等待其他线程执行某些操作。
- 终止(Terminated):线程执行完毕,生命周期结束。
3. 线程的同步
当多个线程访问共享资源时,为了避免数据不一致的问题,通常需要使用同步机制。
3.1 使用 synchronized
关键字
synchronized
关键字用于在方法或代码块上加锁,确保在同一时间内只有一个线程能够执行被同步的代码块。
示例:同步方法
public class Counter {
private int count = 0;
// 使用 synchronized 修饰方法,保证线程安全
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
public static void main(String[] args) {
Counter counter = new Counter();
// 创建两个线程同时访问共享资源
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (