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多线程编程面试必备知识点的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:weapp,转转请注明出处:https://www.dingdanghao.com/article/340601.html
