在Java中,新建线程主要有以下几种方式:
class MyThread extends Thread {
public void run() {
// 新线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyRunnable implements Runnable {
public void run() {
// 新线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 新线程执行的代码
});
thread.start();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(() -> {
// 新线程执行的代码
});
executorService.shutdown();
}
}
这些新建线程的方式在功能上没有本质区别,但在实际使用中有一些差异: