做网红用哪个网站,南京制作网站公司,如何在路由器上做网站转跳,php网站开发人员1#xff09;、继承 Thread 2#xff09;、实现 Runnable 接口 3#xff09;、实现 Callable 接口 FutureTask #xff08;可以拿到返回结果#xff0c;可以处理异常#xff09; 4#xff09;、使用线程池 区别#xff1a;1、2#xff09;不能得到返回值 … 1、继承 Thread 2、实现 Runnable 接口 3、实现 Callable 接口 FutureTask 可以拿到返回结果可以处理异常 4、使用线程池 区别1、2不能得到返回值 3可以获得返回值 但1、2、3都不能控制资源会造成系统资源浪费 只有4可以控制资源优点是性能稳定
所以在在业务代码开发中1、2、3启动线程的方式都不用应该将所有的多线程异步任务交给线程池来执行。
示例代码
public class ThreadTest {public static ExecutorService executorService Executors.newFixedThreadPool(10);public static void main(String[] args)throws Exception {System.out.println(main start.........);//一.extends Thread
// Thread01 thread01new Thread01();
// new Thread(thread01).start();//二.implements Runnable
// Runnable01 runnable01new Runnable01();
// new Thread(runnable01).start();//三.implements Callable
// FutureTaskInteger futureTasknew FutureTask(new Callable01());
// new Thread(futureTask).start();
// //futureTask.get方法会阻塞直到拿到结果
// Integer result futureTask.get();
// System.out.println(main end.........result);//四.使用线程池的方式实现异步编程executorService.execute(new Runnable01());}public static class Thread01 extends Thread{public void run(){System.out.println(当前线程:Thread.currentThread().getId());Integer i10/2;System.out.println(运算结果.........i);}}public static class Runnable01 implements Runnable{Overridepublic void run() {System.out.println(当前线程:Thread.currentThread().getId());Integer i10/2;System.out.println(运算结果.........i);}}public static class Callable01 implements CallableInteger{Overridepublic Integer call() throws Exception {System.out.println(当前线程:Thread.currentThread().getId());Integer i10/2;System.out.println(运算结果.........i);return i;}}
}
线程池执行有2个方法分别是execute()和submit()它们的区别是submit方法执行会有返回值而execute()方法无返回值exeucte()只能接收实现Runnable的类而submit可接收实现Runnable或Callable的类