多线程编程是 Java 中非常重要的一个特性,它使得程序能够并发执行多个任务,从而提高程序的效率。本教程将带你了解 Java 多线程编程的基础知识和实践。

多线程简介

多线程是指在同一程序中同时运行多个线程,每个线程可以执行不同的任务。Java 提供了强大的线程机制,使得多线程编程变得简单而高效。

为什么使用多线程?

  1. 提高程序执行效率:通过并发执行任务,可以充分利用多核处理器的性能。
  2. 改善用户体验:例如,在下载文件时,可以同时显示下载进度和进行其他操作。
  3. 提高资源利用率:例如,在服务器端,可以同时处理多个客户端请求。

创建线程

在 Java 中,创建线程主要有两种方式:

1. 继承 Thread 类

public class MyThread extends Thread {
    @Override
    public void run() {
        // 线程要执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}

2. 实现 Runnable 接口

public class MyRunnable implements Runnable {
    @Override
    public void run() {
        // 线程要执行的任务
    }
}

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new MyRunnable());
        thread.start();
    }
}

线程同步

在多线程环境中,线程之间可能会出现数据竞争和死锁等问题。为了解决这些问题,Java 提供了线程同步机制。

同步方法

public synchronized void method() {
    // 同步代码块
}

同步代码块

public class Main {
    public static void main(String[] args) {
        synchronized (this) {
            // 同步代码块
        }
    }
}

其他同步机制

  • Lock:提供更灵活的同步机制。
  • Semaphore:允许一定数量的线程同时访问某个资源。

互斥锁

互斥锁(Mutex)是一种常用的线程同步机制,它确保同一时间只有一个线程可以访问某个资源。

使用 ReentrantLock

public class Main {
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        lock.lock();
        try {
            // 临界区代码
        } finally {
            lock.unlock();
        }
    }
}

实践案例

以下是一个简单的 Java 多线程程序示例,演示了如何使用线程同步机制来防止数据竞争。

public 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) {
        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();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Count: " + counter.getCount());
    }
}

扩展阅读

线程同步