在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(); // 启动线程
}
}
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 线程执行的任务并返回结果
return "Thread result";
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new MyCallable());
try {
String result = future.get(); // 获取线程执行结果
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
ExecutorService pool = Executors.newFixedThreadPool(10);
pool.submit(() -> {
// 线程执行的任务
});
pool.shutdown(); // 关闭线程池
通过以上方式,Java提供了灵活的线程创建和管理机制,开发者可以根据具体需求选择合适的方法来创建和启动线程。