在Java中,开启线程有多种方法:
public class MyThread extends Thread {
public void run() {
// 线程执行逻辑
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
public class MyRunnable implements Runnable {
public void run() {
// 线程执行逻辑
}
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
ExecutorService executor = Executors.newFixedThreadPool(10);
executor.execute(new Runnable() {
public void run() {
// 线程执行逻辑
}
});
executor.shutdown();
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Integer> future = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
// 线程执行逻辑
return 42;
}
});
executor.shutdown();
try {
int result = future.get();
// 使用得到的结果
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
这些都是Java中常用的开启线程的方法,可以根据具体需求选择适合的方法来创建和管理线程。