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多线程编程面试必备知识点的详细内容。更多信息请关注PHP中文网其他相关文章!