Java异步任务 线程详解(1)
废话不多说,直接上代码。
1.创建线程的四种方式
写main方法
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("main......start.....");
Thread thread = new Thread01();
thread.start();
System.out.println("main......end.....");
}
- 继承Thread
public static class Thread01 extends Thread {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
- 实现Runnable接口
public static class Runable01 implements Runnable {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
- 实现Callable接口
public static class Callable01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程:" + Thread.currentThread().getId());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}
}
通过FutureTask来开启线程
FutureTask<Integer> futureTask = new FutureTask<>(new Callable01());
new Thread(futureTask).start();
System.out.println(futureTask.get());
- 线程池
//线程池,每个系统应该有一个共有的有一个或者是有两个
public static ExecutorService executor = Executors.newFixedThreadPool(10);
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new Runable01());
Future<Integer> submit = service.submit(new Callable01());
submit.get();
service.submit可以得到返回值,而service.execute不能得到返回值
2.四种方法对比
- 1,2种方法不能得到返回值,第三种方法可以得到线程执行的返回值
- 1,2,3都不能控制资源,会导致服务器资源耗尽,服务器崩溃
- 第四种方法可以控制资源,而且性能稳定。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/159008.html