在 Java 中,实现多线程有多种方法:
1.继承 Thread 类: 创建一个类并继承自 java.lang.Thread
类。重写 run()
方法,在 run()
方法中定义线程的执行逻辑。然后实例化该类的对象并调用 start()
方法启动线程。
class MyThread extends Thread {
public void run() {
// 线程的执行逻辑
}
}
MyThread thread = new MyThread();
thread.start();
2.实现 Runnable 接口: 创建一个类实现 java.lang.Runnable
接口,重写 run()
方法。然后将实现了 Runnable
接口的类传递给 Thread
类的构造方法,并调用 start()
方法启动线程。
class MyRunnable implements Runnable {
public void run() {
// 线程的执行逻辑
}
}
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
3.使用匿名类或 Lambda 表达式: 在创建线程时可以直接使用匿名类或 Lambda 表达式来实现 Runnable
接口中的 run()
方法。
Runnable myRunnable = () -> {
// 线程的执行逻辑
};
Thread thread = new Thread(myRunnable);
thread.start();
4. 实现 Callable 接口: 与 Runnable
类似,不同之处在于 Callable
接口的 call()
方法可以返回结果或抛出异常。Callable
需要结合 ExecutorService
的 submit()
方法来执行。
class MyCallable implements Callable<Integer> {
public Integer call() {
// 线程的执行逻辑,并返回结果
return 42;
}
}
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(new MyCallable());
try {
Integer result = future.get();
// 使用返回的结果
} catch (InterruptedException | ExecutionException e) {
// 处理异常
} finally {
executor.shutdown();
}
这些方法都可以用来创建和管理线程,在不同的场景下可以根据需求选择合适的方式来实现多线程。
因篇幅问题不能全部显示,请点此查看更多更全内容