Java線程創(chuàng)建的方法
在Java中,我們可以使用不同的方式來(lái)創(chuàng)建線程。下面介紹三種常用的方法: 繼承Thread類創(chuàng)建線程 通過(guò)繼承Thread類,我們可以創(chuàng)建一個(gè)新的線程類,并重寫(xiě)該類的run()方法。在run(
在Java中,我們可以使用不同的方式來(lái)創(chuàng)建線程。下面介紹三種常用的方法:
- 繼承Thread類創(chuàng)建線程
- 實(shí)現(xiàn)Runnable接口創(chuàng)建線程
- 使用Callable和Future創(chuàng)建線程
通過(guò)繼承Thread類,我們可以創(chuàng)建一個(gè)新的線程類,并重寫(xiě)該類的run()方法。在run()方法中定義線程需要執(zhí)行的任務(wù),也稱為線程的執(zhí)行體。
public class MyThread extends Thread {
public void run() {
// 線程執(zhí)行的任務(wù)
}
}
public class Main {
public static void main(String[] args) {
MyThread thread new MyThread();
(); // 啟動(dòng)線程
}
}
通過(guò)實(shí)現(xiàn)Runnable接口,我們可以創(chuàng)建一個(gè)實(shí)現(xiàn)了Runnable接口的類,并重寫(xiě)run()方法。然后,通過(guò)將實(shí)現(xiàn)類的實(shí)例作為參數(shù)傳遞給Thread類的構(gòu)造方法,創(chuàng)建一個(gè)Thread對(duì)象。
public class MyRunnable implements Runnable {
public void run() {
// 線程執(zhí)行的任務(wù)
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable new MyRunnable();
Thread thread new Thread(runnable);
(); // 啟動(dòng)線程
}
}
通過(guò)實(shí)現(xiàn)Callable接口,我們可以創(chuàng)建一個(gè)實(shí)現(xiàn)了Callable接口的類,并重寫(xiě)call()方法。然后,創(chuàng)建一個(gè)FutureTask對(duì)象,將Callable對(duì)象作為參數(shù)傳遞給FutureTask的構(gòu)造方法。
import ;
import ;
public class MyCallable implements Callablelt;Stringgt; {
public String call() throws Exception {
// 線程執(zhí)行的任務(wù)
return "線程執(zhí)行結(jié)果";
}
}
public class Main {
public static void main(String[] args) {
MyCallable callable new MyCallable();
FutureTasklt;Stringgt; futureTask new FutureTask<>(callable);
Thread thread new Thread(futureTask);
(); // 啟動(dòng)線程
}
}
上述是Java中線程創(chuàng)建的三種常用方法,根據(jù)實(shí)際需求選擇合適的方式來(lái)創(chuàng)建和啟動(dòng)線程。