多线程的创建方式有哪些?
-
1、「继承Thread类」,重写run()方法
public class Demo extends Thread{
//重写父类Thread的run()
public void run() {
}
public static void main(String[] args) {
Demo d1 = new Demo();
Demo d2 = new Demo();
d1.start();
d2.start();
}
}
-
2.「实现Runnable接口」,重写run()
public class Demo2 implements Runnable{
//重写Runnable接口的run()
public void run() {
}
public static void main(String[] args) {
Thread t1 = new Thread(new Demo2());
Thread t2 = new Thread(new Demo2());
t1.start();
t2.start();
}
}
-
3.「实现 Callable 接口」
public class Demo implements Callable<String>{
public String call() throws Exception {
System.out.println("正在执行新建线程任务");
Thread.sleep(2000);
return "结果";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Demo d = new Demo();
FutureTask<String> task = new FutureTask<>(d);
Thread t = new Thread(task);
t.start();
//获取任务执行后返回的结果
String result = task.get();
}
}
-
4.「使用线程池创建」
public class Demo {
public static void main(String[] args) {
Executor threadPool = Executors.newFixedThreadPool(5);
for(int i = 0 ;i < 10 ; i++) {
threadPool.execute(new Runnable() {
public void run() {
//todo
}
});
}
}
}