Java 创建多线程的4种方式包括以下几种:
- 继承Thread类
定义子类:通过继承Thread类,并重写其run()方法来定义线程要执行的任务。
创建实例并启动:创建该子类的实例,然后调用start()方法启动线程。
示例代码:
public class Mythread extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(this.getName() + ":" + i);
}
}
public static void main(String[] args) {
Mythread t1 = new Mythread();
Mythread t2 = new Mythread();
Mythread t3 = new Mythread();
t1.start();
t2.start();
t3.start();
}
}
- 实现Runnable接口
定义实现类:实现Runnable接口,并重写其run()方法。
创建Thread对象并启动:将实现类实例作为参数传给Thread对象的构造函数,然后调用start()方法启动线程。
示例代码:
public class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(myThread, "线程1");
Thread thread2 = new Thread(myThread, "线程2");
Thread thread3 = new Thread(myThread, "线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
- 使用Callable和Future接口
定义Callable实现类:实现Callable接口并重写其call()方法。
使用FutureTask包装:用FutureTask类包装Callable对象,并将其传递给Thread对象。
获取结果:通过FutureTask对象的get()方法获取线程执行的结果。
示例代码:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MyThread implements Callable<String> {
@Override
public String call() throws Exception {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
return "Hello Tom";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
MyThread d = new MyThread();
FutureTask<String> futureTask = new FutureTask<>(d);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("返回值:" + futureTask.get()); // 阻塞直到任务完成并返回结果
}
}
- 使用线程池(Executor)
创建线程池:通过Executors工具类创建一个线程池,如newFixedThreadPool、newCachedThreadPool等。
提交任务:将实现了Runnable或Callable接口的任务提交给线程池执行。
示例代码:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyThreadPool implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++) {
MyThreadPool myThreadPool = new MyThreadPool();
executorService.submit(myThreadPool); // 提交任务到线程池
}
executorService.shutdown(); // 关闭线程池
}
}
Java中创建多线程的方式主要包括继承Thread类、实现Runnable接口、使用Callable和Future接口以及利用线程池。每种方式都有其适用场景和特点,可以根据具体需求选择合适的方式来实现多线程编程。