首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 多線程啟動的三種姿勢:Thread 繼承、Runnable 實現、Lambda 匿名類對比

     編輯:Java 相關知識

核心區別:start() vs run()

  • start():請求 JVM 分配新線程,**異步**執行 run();
  • run():普通方法調用,**同步**在當前線程執行,不會開啟新線程。

方式一:繼承 Thread 類

public class ThreadDemo1 extends Thread {
    private final String msg;
    private final int count;

    public ThreadDemo1(String msg, int count) {
        this.msg = msg; this.count = count;
        setName(msg + "-Runner");
    }

    @Override public void run() {
        while (count-- > 0) {
            System.out.println(msg);
            sleepQuietly(100);
        }
        System.out.println(msg + " all done.");
    }

    private void sleepQuietly(long ms) {
        try { Thread.sleep(ms); } catch (InterruptedException ignored) {}
    }

    public static void main(String[] args) {
        new ThreadDemo1("Hello from X", 10).start();
        new ThreadDemo1("Hello from Y", 15).start();
    }
}

方式二:實現 Runnable 介面(推薦)

public class ThreadDemo2 implements Runnable {
    private final String msg;
    private final int count;

    public ThreadDemo2(String msg, int count) {
        this.msg = msg; this.count = count;
        new Thread(this, msg + "-Runner").start();
    }

    @Override public void run() {
        while (count-- > 0) {
            System.out.println(msg);
            sleepQuietly(100);
        }
        System.out.println(msg + " all done.");
    }
    // main 同方式一
}

優勢:避免單繼承限制,邏輯與線程控制解耦,易於提交給線程池。

方式三:匿名內部類 / Lambda(JDK 8+)

public class ThreadDemo3 {
    public static void main(String[] args) {
        // 匿名類
        new Thread(new Runnable() {
            @Override public void run() { /* ... */ }
        }, "Anon-Runner").start();

        // Lambda(函數式介面)
        new Thread(() -> {
            for (int i = 10; i > 0; i--) {
                System.out.println("Lambda: " + i);
                sleepQuietly(100);
            }
        }, "Lambda-Runner").start();
    }
    // sleepQuietly 同前
}

執行結果示例(交錯輸出)

Hello from X
Hello from Y
Hello from X
Hello from Y
...
Hello from X all done.
Hello from Y all done.

進階:線程池統一管理(生產環境標準)

ExecutorService pool = Executors.newFixedThreadPool(4);
pool.submit(() -> { /* task */ });
pool.shutdown();
  • 避免頻繁創建/銷毀線程開銷;
  • 可控制併發數、隊列長度、拒絕策略;
  • 支援 Future/CompletableFuture 獲取結果。

常見誤區

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
錯誤寫法後果正確寫法
new MyThread().run()主線程同步執行,無併發new MyThread().start()
在 run() 內死循環無 sleep佔用 CPU 100%,導致饑餓加 Thread.sleep 或 wait/notify
共享變量無同步數據競爭、可見性問題volatile/AtomicInteger/synchronized