创建线程的方式_创建线程有几种不同的方式?

方式可以用来创建线程

1)继承Thread类

2)实现Runnable接口

3)应用程序可以适用Executor框架来创建线程池

实现了Runnable接口这种方式更受欢迎,因为这不需要继承Thread类。在应用设计中已经继承了别的对象的情况下,这需要多继承,而Java不支持多继承,只能实现接口。同时,线程池也是非常高效的,很容易实现和适用。

举例:

例1:

public class ThreadDemo {
public static void main(String[] args) {
Runnable task = () -> {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(100);
}
} catch (Exception e) {
}
System.out.println("child thread exit.");
};

Thread t1 = new Thread(task);
System.out.println("Child Thread: " + t1);
t1.start();

try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (Exception e) {
}
System.out.println("Main thread exit.");
}
}

例2:

public class ExecutorsTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> ft = executor.submit(() -> {
System.out.println("Hello Thread!");
return "sucess";
});
try {
System.out.println("return : " + ft.get());
} catch (Exception e) {
e.printStackTrace();
}
executor.shutdown();

}
}

希望对各位正在准备面试的小伙伴有所帮助!


《JAVA面试机经基础篇》 郭屹老师著
2b0db3626826ea925dcad60d2294156c.png
百度搜索JAVA面试机经基础篇即可
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值