共計 825 個字符,預(yù)計需要花費 3 分鐘才能閱讀完成。
以下是一個簡單的 Java 多線程編程實例:
public class MultiThreadExample implements Runnable {
private String threadName;
public MultiThreadExample(String threadName) {this.threadName = threadName;}
@Override
public void run() {System.out.println("線程" + threadName + "正在運行");
try {for (int i = 5; i > 0; i--) {System.out.println("線程" + threadName + ":" + i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {System.out.println("線程" + threadName + "被中斷");
}
System.out.println("線程" + threadName + "運行結(jié)束");
}
public static void main(String[] args) {Thread thread1 = new Thread(new MultiThreadExample("線程 1"));
Thread thread2 = new Thread(new MultiThreadExample("線程 2"));
thread1.start();
thread2.start();}
}
在這個例子中,我們創(chuàng)建了一個 MultiThreadExample
類實現(xiàn)了 Runnable
接口。這個類包含了一個帶有線程名稱參數(shù)的構(gòu)造函數(shù)和一個 run
方法。run
方法定義了線程的執(zhí)行邏輯,輸出線程名稱和每秒倒計時 5 次。
在 main
方法中,我們創(chuàng)建了兩個線程對象,并分別傳入不同的線程名稱。然后,我們調(diào)用 start
方法啟動線程。
當我們運行這個程序時,會看到兩個線程同時開始運行,并且輸出各自的倒計時。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完
發(fā)表至: Java
2023-12-21