java 多线程编程包括创建和管理线程,以实现并发执行。它涵盖了线程的基本概念、同步、线程池和实际情况:线程是一个轻量级的过程,共享内存空间,允许并发执行。通过锁定或原子操作,同步确保共享资源的访问安全。线程池管理线程,提高性能,减少创建和销毁成本。实际的战斗示例使用多线程并行扫描目录中的文件。

Java 多线程编程面试必备知识点
1. 线程的基本概念
- 线程是操作系统中的轻量级过程,与过程共享相同的内存空间。
- 允许在同一程序中执行多个独立的任务。
代码示例:
class MyThread extends Thread {
public void run() {
System.out.println("This is a thread");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}登录后复制
2. 线程的同步
- 在访问共享资源时,线程同步确保避免数据竞争。
- 通过使用锁机制或原子操作,可以实现同步。
代码示例(使用 synchronized):
class Counter {
private int count;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
counter.increment();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount()); // 输出:20000
}
}登录后复制
3. 线程池
- 线程池是一组管理线程的资源。
- 它可以提高性能,减少创建和销毁线程的成本。
代码示例(使用 ThreadPoolExecutor):
ExecutorService executor = Executors.newFixedThreadPool(5);
for (int i = 0; i < 10; i++) {
executor.submit(() -> {
System.out.println("This is a thread from the pool");
});
}
executor.shutdown();登录后复制
4. 实战案例:文件扫描
- 在大目录中使用多线程并行扫描文件。
代码示例:
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FileScanner {
private static void scan(File dir) {
File[] files = dir.listFiles();
if (files == null)
return;
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for (File f : files) {
executor.submit(() -> {
if (f.isDirectory())
scan(f);
else
System.out.println(f.getAbsolutePath());
});
}
executor.shutdown();
}
public static void main(String[] args) {
File root = new File("..."); // 替换为扫描目录
scan(root);
}
}登录后复制
以上是Java多线程编程面试必备知识点的详细内容。请关注图灵教育的其他相关文章!