答案: 線程(cheng)是執行程(cheng)序的基本單元,可以(yi)同時運行多個線程(cheng)以(yi)實(shi)現并發性(xing)。在Java中,線程(cheng)通過Thread類來(lai)表示和操作(zuo)。
要創建和啟(qi)動線程(cheng),可以(yi)通過以(yi)下步驟:
創建Thread類的(de)子類,并重寫其run()方法(fa),該方法(fa)包(bao)含了線程的(de)執(zhi)行邏輯。
在子類(lei)中實(shi)例化Thread對象,并調用其start()方(fang)法(fa)。start()方(fang)法(fa)會啟動新線(xian)程,并自動調用子類(lei)的(de)run()方(fang)法(fa)。
示例代碼如下:
class MyThread extends Thread {
public void run() {
// 線程的執行邏輯
System.out.println("Thread is running.");
}
}
public class Main {
public static void main(String[] args) {
// 創建并啟動線程
MyThread thread = new MyThread();
thread.start();
}
}
上(shang)述代(dai)碼(ma)創建了一(yi)個繼承自Thread類的子類MyThread,并在其run()方法(fa)中定義了線程的執行邏輯(ji)。在主(zhu)程序中,實(shi)例(li)化MyThread對(dui)象并調用其start()方法(fa),即可(ke)創建并啟動(dong)新線程。
注意:除了繼承(cheng)Thread類,還可以(yi)通過實現Runnable接口(kou)來創(chuang)建線程(cheng),并將其作為參數傳遞給Thread類的(de)構造函數。這種方(fang)式(shi)更常用,因為Java不支持多重繼承(cheng)。