创建线程有哪几种方式?
- 通过扩展 Thread 类来创建多线程
- 通过实现 Runnable 接口来创建多线程
- 实现 Callable 接口,通过 FutureTask 接口创建线程。
- 使用 Executor 框架来创建线程池。
继承 Thread 创建线程:
代码如下。run()方法是由jvm创建完操作系统级线程后回调的方法,不可以手动调用,手动调用相当于调用普通方法
publicclassMyThreadextendsThread { publicMyThread() { } publicvoidrun() { for (inti=0; i<10; i++) { System.out.println(Thread.currentThread() +":"+i); } } publicstaticvoidmain(String[] args) { MyThreadmThread1=newMyThread(); MyThreadmThread2=newMyThread(); MyThreadmyThread3=newMyThread(); mThread1.start(); mThread2.start(); myThread3.start(); } }
Runnable 创建线程代码:
publicclassRunnableTest { publicstaticvoidmain(String[] args){ Runnable1r=newRunnable1(); Threadthread=newThread(r); thread.start(); System.out.println("主线程:["+Thread.currentThread().getName()+"]"); } } classRunnable1implementsRunnable{ publicvoidrun() { System.out.println("当前线程:"+Thread.currentThread().getName()); } }
实现Runnable接口比继承Thread类所具有的优势:
1. 可以避免java中的单继承的限制
2. 线程池只能放入实现Runable或Callable类线程,不能直接放入继承Thread的类
Callable 创建线程代码:
publicclassCallableTest { publicstaticvoidmain(String[] args) { Callable1c=newCallable1(); //异步计算的结果FutureTask<Integer>result=newFutureTask<>(c); newThread(result).start(); try { //等待任务完成,返回结果intsum=result.get(); System.out.println(sum); } catch (InterruptedException|ExecutionExceptione) { e.printStackTrace(); } } } classCallable1implementsCallable<Integer> { publicIntegercall() throwsException { intsum=0; for (inti=0; i<=100; i++) { sum+=i; } returnsum; } }
使用 Executor 创建线程代码:
publicclassExecutorsTest { publicstaticvoidmain(String[] args) { //获取ExecutorService实例,生产禁用,需要手动创建线程池ExecutorServiceexecutorService=Executors.newCachedThreadPool(); //提交任务executorService.submit(newRunnableDemo()); } } classRunnableDemoimplementsRunnable { publicvoidrun() { System.out.println("大彬"); } }