在Java中,实现线程主要有三种方式:继承Thread类、实现Runnable接口、实现Callable接口。以下是具体的实现方式及其特点:
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 myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 线程执行的代码,并返回结果
return "Callable result";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
String result = futureTask.get(); // 获取线程执行的结果
}
}
通过上述方式,Java提供了灵活且强大的线程实现机制,以适应不同的应用场景和需求。