创建线程有哪几种方式?3种
程序员文章站
2022-05-04 08:49:52
1.继承Thread类型重写run 方法public class ThreadDemoTest extends Thread{ @Override public void run() { System.out.println("通过继承Thread类重写run方法实现接口!"); } public static void main(String[] args) { ThreadDemoTest threadDemoTest = new T...
1.继承Thread类型重写run 方法
public class ThreadDemoTest extends Thread{
@Override
public void run() {
System.out.println("通过继承Thread类重写run方法实现接口!");
}
public static void main(String[] args) {
ThreadDemoTest threadDemoTest = new ThreadDemoTest();
threadDemoTest.run();
}
}
2.实现Runnable接口
public class RunnableDemoTest implements Runnable{
public void run() {
System.out.println("实现Runnable开启线程!");
}
public static void main(String[] args) {
Thread thread = new Thread(new RunnableDemoTest());
thread.start();
}
}
3.实现Callable接口
public class CallableDemoTest implements Callable {
public Object call() {
return "HelloCallable!";
}
@Test
public void test() throws ExecutionException, InterruptedException {
CallableDemoTest callableDemoTest = new CallableDemoTest();
FutureTask futureTask = new FutureTask(callableDemoTest);
Thread thread = new Thread(futureTask);
thread.start();
//获取返回值
futureTask.get();
}
}
本文地址:https://blog.csdn.net/sinat_41920065/article/details/107455667
上一篇: 代码实现还原Spring基本功能,实现IOC,DI,AOP
下一篇: Java基础学习第一天