Java创建线程三种方式的优缺点
Java创建线程主要有三种方式:继承Thread类创建线程、实现Runnable接口创建线程和实现Callable和Future创建线程。
继承Thread类
public class Thread1 extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(getName() + ": " + i);
}
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
if (i == 2) {
new Thread1().start();
new Thread1().start();
}
}
}
}
实现Runnable接口
public class Thread2 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) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
if (i == 2) {
Thread2 thread2 = new Thread2();
new Thread(thread2).start();
new Thread(thread2).start();
}
}
}
}
实现Callable接口
FutureTask类包装Callable对象时,封装了Callable对象的call()方法的返回值。
class Thread3 implements Callable {
@Override
public Integer call() throws Exception {
int i = 0;
for (; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
return i;
}
public static void main(String[] args) {
Thread3 thread3 = new Thread3();
FutureTask<Integer> futureTask = new FutureTask<Integer>(thread3);
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " :" + i);
if (i == 2) {
new Thread(futureTask, "有返回值的线程").start();
}
}
try {
System.out.println("子线程返回值: " + futureTask.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
三种方式优缺点
采用实现接口(Runnable和Callable)的方式,线程类还可以继承其他的类。实现接口的线程对象还可以用来创建多个线程,可以实现资源共享。缺点是不能使用this指针来获取线程的名字等。
采用继承Thread类的方式,线程不能继承其他的类,但是Thread类中有getName方法,因为可以直接使用this.getName()来获取当前线程的名字。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
相关文章
SpringBoot接口返回的数据时间与实际相差8小时问题排查方式
文章描述了在部署SpringBoot应用到容器中时遇到请求接口返回时间与实际相差8小时的问题,并详细分析了可能的原因及具体的排查步骤和解决方案,总结指出,环境初始时区未配置是根本原因,建议在应用部署前配置好时区2025-02-02
SpringCloud服务接口调用OpenFeign及使用详解
这篇文章主要介绍了SpringCloud服务接口调用——OpenFeign,在学习Ribbon时,服务间调用使用的是RestTemplate+Ribbon实现,而Feign在此基础上继续进行了封装,使服务间调用变得更加方便,需要的朋友可以参考下2023-04-04


最新评论