import java.util.concurrent.*;
class Mythread1 extends Thread{
@Override
public void run(){
System.out.println("通过继承Thread类"+Thread.currentThread().getName());
}
}
class Mythread2 implements Runnable{
@Override
public void run() {
System.out.println("通过实现Runnable接口,不会返回结果或抛出异常");
}
}
class Mythread3 implements Callable{
@Override
public String call() throws Exception {
System.out.println("通过实现Callable接口,会返回结果或抛出异常");
return "Callable返回的结果";
}
}
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService ex = new ThreadPoolExecutor(5,10,1,TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
new ThreadPoolExecutor.CallerRunsPolicy());
//Thread()要求传入一个Runnable类型的变量
new Mythread1().start();
new Thread(new Mythread2());
new Thread(new FutureTask<String>(new Mythread3()));
ex.execute(new Mythread2());
Future<String> submit = ex.submit(new Mythread3());
System.out.println(submit.get());
for(int i = 0;i<10;i++){
ex.execute(new Mythread1());
}
ex.shutdown();
}
}
线程创建的四种方式
最新推荐文章于 2024-10-06 20:16:20 发布