Java中创建线程的三种方式及其优缺点

时间:2023-03-08 17:53:14

1.自定义一个继承Thread的类,由于Java的单继承特性,限制了该类的扩展性。

2.实现Runnable接口,重写run()方法。

3.实现Callable接口,重写call方法。线程执行体可以有返回值,并且可以抛出异常。

 import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask; public class Main {
public static void main(String[] args) {
// 1.继承Thread类
new DefineThread().start();
// 2.实现Runnable接口
new Thread(new DefineRunnable()).start();
// 3.实现Callable接口
new Thread(futureTask).start();
String result = "";
try {
result = futureTask.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
//ExecutionException封装了call()方法抛出的异常
e.printStackTrace();
e.getCause();
//getCause()方法把被包装的原始异常提取出来
}
System.out.println(result);
} static class DefineThread extends Thread { @Override
public void run() {
for (int i = 0; i < 100; i++) {
String name2 = getName();
try {
sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name2 + ": " + i);
}
}
} static class DefineRunnable implements Runnable { @Override
public void run() {
for (int i = 0; i < 100; i++) {
// String name2 = getName();
String name = Thread.currentThread().getName(); // 实现runnable接口,使用Thread类的currentThread()获取当前线程对象
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(name + ": " + i);
}
}
} static FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() { @Override
public String call() throws InterruptedException {
String name = "";
int i = 0;
for (; i < 100; i++) {
name = Thread.currentThread().getName();
Thread.currentThread().sleep(100);
System.out.println(name + ": " + i);
}
return name + " ----->Result=" + i;
}
});
}