在Java中,创建线程有两种主要方法:
class MyThread extends Thread {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.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 MyRunnable implements Runnable {
public void run() {
// 线程执行的代码
}
}
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
// 线程执行的代码
});
thread.start(); // 启动线程
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
public String call() throws Exception {
// 线程执行的代码,返回一个结果
return "任务结果";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<String> future = executorService.submit(new MyCallable());
String result = future.get(); // 获取任务结果
executorService.shutdown(); // 关闭线程池
}
}
这些方法可以根据具体需求选择使用。对于简单的任务,可以使用继承Thread类或实现Runnable接口的方式。对于更复杂的任务,可以使用Java 8的lambda表达式、ExecutorService和Callable接口来实现多线程编程。