Java中创建子线程的方法有以下几种:
public class MyThread extends Thread {
@Override
public void run() {
// 子线程的任务逻辑
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
public class MyRunnable implements Runnable {
@Override
public void run() {
// 子线程的任务逻辑
}
public static void main(String[] args) {
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 子线程的任务逻辑
return "子线程的返回结果";
}
public static void main(String[] args) {
MyCallable callable = new MyCallable();
ExecutorService executorService = Executors.newFixedThreadPool(1);
Future<String> future = executorService.submit(callable);
try {
String result = future.get();
System.out.println("子线程的返回结果:" + result);
} catch (Exception e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
这些方法都可以创建一个子线程并执行一些任务逻辑,具体使用哪种方法取决于需求和代码的结构。