Java 多线程实现方式详解及示例
Java 实现多线程的方式有以下几种:
- 继承 Thread 类:定义一个类继承 Thread 类,并重写 run() 方法,在 run() 方法中定义线程的任务。然后创建该类的对象,并调用 start() 方法启动线程。
示例代码如下:
class MyThread extends Thread {
public void run() {
// 线程的任务
System.out.println('Thread ' + Thread.currentThread().getId() + ' is running');
}
}
public class Main {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start();
thread2.start();
}
}
- 实现 Runnable 接口:定义一个类实现 Runnable 接口,并实现 run() 方法,在 run() 方法中定义线程的任务。然后创建该类的对象,并将其作为参数传递给 Thread 类的构造方法,最后调用 start() 方法启动线程。
示例代码如下:
class MyRunnable implements Runnable {
public void run() {
// 线程的任务
System.out.println('Thread ' + Thread.currentThread().getId() + ' is running');
}
}
public class Main {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
- 使用 Callable 和 Future:定义一个类实现 Callable 接口,并实现 call() 方法,在 call() 方法中定义线程的任务。然后创建该类的对象,并将其作为参数传递给 ExecutorService 的 submit() 方法,最后通过 Future 对象获取线程的返回结果。
示例代码如下:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
public String call() {
// 线程的任务
return 'Thread ' + Thread.currentThread().getId() + ' is running';
}
}
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future1 = executor.submit(new MyCallable());
Future<String> future2 = executor.submit(new MyCallable());
try {
System.out.println(future1.get());
System.out.println(future2.get());
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();
}
}
以上是 Java 实现多线程的几种方式,可以根据具体的需求选择适合的方式。
原文地址: http://www.cveoy.top/t/topic/fPGX 著作权归作者所有。请勿转载和采集!