方式可以用来创建线程
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面试机经基础篇》 郭屹老师著