Java開啟線程的方式有以下幾種:
示例代碼:
class MyThread extends Thread {
public void run() {
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
示例代碼:
class MyRunnable implements Runnable {
public void run() {
// 線程執(zhí)行的代碼
}
}
public class Main {
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
示例代碼:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread() {
public void run() {
// 線程執(zhí)行的代碼
}
};
thread.start();
}
}
示例代碼:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(new Runnable() {
public void run() {
// 線程執(zhí)行的代碼
}
});
executor.shutdown();
}
}
上述是常用的幾種開啟線程的方式,根據(jù)實(shí)際需求選擇適合的方式。