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中文網其他相關文章!