溫馨提示×

java多線程編程實例

小云
94
2023-08-16 12:49:18
欄目: 編程語言

以下是一個簡單的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方法啟動線程。

當我們運行這個程序時,會看到兩個線程同時開始運行,并且輸出各自的倒計時。

0