在Java中,有以下几种实现多线程的方式:
class MyThread extends Thread {
public void run() {
// 线程要执行的代码
}
}
MyThread thread = new MyThread();
thread.start();
class MyRunnable implements Runnable {
public void run() {
// 线程要执行的代码
}
}
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
class MyCallable implements Callable<Integer> {
public Integer call() {
// 线程要执行的代码
return result;
}
}
ExecutorService executor = Executors.newFixedThreadPool(1);
MyCallable callable = new MyCallable();
Future<Integer> future = executor.submit(callable);
Integer result = future.get();
Runnable runnable = new Runnable() {
public void run() {
// 线程要执行的代码
}
};
Thread thread = new Thread(runnable);
thread.start();
或者
Runnable runnable = () -> {
// 线程要执行的代码
};
Thread thread = new Thread(runnable);
thread.start();
以上是几种常见的实现多线程的方式,每种方式都有其适用的场景,可以根据具体需求选择合适的方式来实现多线程。