在Java中,创建线程主要有以下几种方式:
1、继承Thread
类
通过继承Thread
类来创建线程是最基本的一种方式。你需要创建一个继承自Thread
类的子类,并重写其run
方法。然后,你可以创建该子类的实例来创建新的线程。最后,通过调用线程实例的start()
方法来启动线程。
class MyThread extends Thread {
public void run() {
System.out.println("线程运行中");
}
}
public class Test {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();
}
}
2、实现Runnable
接口
实现Runnable
接口是另一种创建线程的方式。你需要创建一个实现了Runnable
接口的类的实例,该类必须实现run
方法。然后,你可以创建Thread
类的一个实例,将Runnable
实现类的实例作为构造器参数传递给它。最后,通过调用Thread
实例的start()
方法来启动线程。
class MyRunnable implements Runnable {
public void run() {
System.out.println("线程运行中");
}
}
public class Test {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
}
}
3、实现Callable
接口结合FutureTask
类
从Java 5开始,Callable
接口被引入,它类似于Runnable
接口,但Callable
可以返回值,并且可以抛出异常。FutureTask
类实现了Future
和Runnable
接口,它可以把Callable
转换成Runnable
,并且由于FutureTask
实现了Future
接口,所以我们可以从中获取异步计算的结果。
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
public Integer call() throws Exception {
return 123;
}
}
public class Test {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task = new FutureTask<>(new MyCallable());
new Thread(task).start();
System.out.println(task.get()); // 阻塞直到计算完成,并获取结果
}
}
4、使用线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new Runnable() {
public void run() {
System.out.println("线程运行中");
}
});
executor.shutdown(); // 不再提交任务,关闭线程池
}
}