创建多线程有哪几种方式
创建多线程共有四种方式:
- 继承Thread类创建多线程
- 实现Runnable接口创建多线程
- 实现Callable接口通过FutureTask包装器来创建Thread多线程
- 使用ExecutorService、Callable、Future实现有返回结果的线程。
1. 继承Thread类
2. 实现Runnable接口
3. Callable + Future
4. ExecutorService + Callable + Future
代码如下:
- 继承Thread类
package com.dazhi.thread.multithread;
/**
* 多线程创建,继承
* @author dazhi
*/
public class MyThread extends Thread{
@Override
public void run() {
for (int i=0; i<10; i++) {
System.out.println(Thread.currentThread().getName() +":"+ i);
}
}
public static void main(String[] args) throws InterruptedException {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
thread1.start();
thread2.start();
thread3.start();
}
}
- 实现Runnable接口
package com.dazhi.thread.multithread;
/**
* 多线程创建, 实现Runnable
* @author dazhi
*/
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int i=0; i<10; i++) {
System.out.println(Thread.currentThread().getName() +":"+ i);
}
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread1 = new Thread(myRunnable, "thread1");
Thread thread2 = new Thread(myRunnable, "thread2");
Thread thread3 = new Thread(myRunnable, "thread3");
thread1.start();
thread2.start();
thread3.start();
}
}
- 实现Callable
package com.dazhi.thread.multithread;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
/**
* 多线程创建, 实现Callable接口
* @author dazhi
*/
public class MyCallable implements Callable<Object> {
@Override
public Object call() throws Exception {
return "嗨,你好";
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask<Object> futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
// 可以拿到线程的返回值
System.out.println(futureTask.get());
}
}
// 运行结果
嗨,你好
Process finished with exit code 0
- ExecutorService + Callable + Future
package com.dazhi.thread.multithread;
import java.util.concurrent.*;
/**
* 多线程创建, ExecutorService + Callable + Future
* @author dazhi
*/
public class MyExecutors {
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 不提倡的方式创建线程池方式。为了方便就这样写了
ExecutorService executorService = Executors.newFixedThreadPool(5);
Future<Integer> submit = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return 1234;
}
});
executorService.shutdown();
System.out.println(submit.get());
}
}
// 运行结果
1234
Process finished with exit code 0
// 不提倡创建线程池的原因