Java开启线程的方式有以下几种:
示例代码:
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
示例代码:
class MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
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() {
// 线程执行的代码
}
};
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() {
// 线程执行的代码
}
});
executor.shutdown();
}
}
上述是常用的几种开启线程的方式,根据实际需求选择适合的方式。