溫馨提示×

java怎么使用匿名內(nèi)部類創(chuàng)建線程

小億
118
2023-12-27 23:54:22
欄目: 編程語言

在Java中,使用匿名內(nèi)部類創(chuàng)建線程的步驟如下:

  1. 創(chuàng)建一個Thread對象,并使用匿名內(nèi)部類作為參數(shù)傳遞給Thread的構(gòu)造函數(shù)。
  2. 在匿名內(nèi)部類中重寫run()方法,定義線程的執(zhí)行邏輯。
  3. 調(diào)用start()方法啟動線程。

以下是示例代碼:

public class Main {
    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // 線程執(zhí)行的邏輯
                System.out.println("Thread running");
            }
        });

        thread.start();
    }
}

在上面的示例中,使用匿名內(nèi)部類實現(xiàn)了Runnable接口,并在run()方法中定義了線程的執(zhí)行邏輯。然后,將匿名內(nèi)部類對象傳遞給Thread的構(gòu)造函數(shù)創(chuàng)建了一個線程對象。最后,調(diào)用start()方法啟動線程。

0