Java创建多线程的8种代码方式
1、繼承Thread類,重寫run()方法
//方式1
package cn.itcats.thread.Test1;public class Demo1 extends Thread{//重寫的是父類Thread的run()public void run() {System.out.println(getName()+"is running...");}public static void main(String[] args) {Demo1 demo1 = new Demo1();Demo1 demo2 = new Demo1();demo1.start();demo2.start();} }2、實現Runnable接口,重寫run()
實現Runnable接口只是完成了線程任務的編寫
若要啟動線程,需要new Thread(Runnable target),再有thread對象調用start()方法啟動線程
此處我們只是重寫了Runnable接口的Run()方法,并未重寫Thread類的run(),讓我們看看Thread類run()的實現
本質上也是調用了我們傳進去的Runnale target對象的run()方法
所以第二種創建線程的實現代碼如下:
package cn.itcats.thread.Test1;/*** 第二種創建啟動線程的方式* 實現Runnale接口* @author fatah*/ public class Demo2 implements Runnable{//重寫的是Runnable接口的run()public void run() {System.out.println("implements Runnable is running");}public static void main(String[] args) {Thread thread1 = new Thread(new Demo2());Thread thread2 = new Thread(new Demo2());thread1.start();thread2.start();} }實現Runnable接口相比第一種繼承Thread類的方式,使用了面向接口,將任務與線程進行分離,有利于解耦
3、匿名內部類的方式
適用于創建啟動線程次數較少的環境,書寫更加簡便
具體代碼實現:
4、帶返回值的線程(實現implements Callable<返回值類型>)
以上兩種方式,都沒有返回值且都無法拋出異常。
Callable和Runnbale一樣代表著任務,只是Callable接口中不是run(),而是call()方法,但兩者相似,即都表示執行任務,call()方法的返回值類型即為Callable接口的泛型
具體代碼實現:
5、定時器(java.util.Timer)
關于Timmer的幾個構造方法
執行定時器任務使用的是schedule方法:
我們發現Timer有不可控的缺點,當任務未執行完畢或我們每次想執行不同任務時候,實現起來比較麻煩。這里推薦一個比較優秀的開源作業調度框架“quartz”。
6、線程池的實現(java.util.concurrent.Executor接口)
降低了創建線程和銷毀線程時間開銷和資源浪費
具體代碼實現:
運行完畢,但程序并未停止,原因是線程池并未銷毀,若想銷毀調用threadPool.shutdown(); 注意需要把我上面的
Executor threadPool = Executors.newFixedThreadPool(10); 改為
ExecutorService threadPool = Executors.newFixedThreadPool(10); 否則無shutdown()方法
若創建的是CachedThreadPool則不需要指定線程數量,線程數量多少取決于線程任務,不夠用則創建線程,夠用則回收。
7、Lambda表達式的實現(parallelStream)
package cn.itcats.thread.Test1;import java.util.ArrayList; import java.util.Arrays; import java.util.List;/*** 使用Lambda表達式并行計算* parallelStream* @author fatah*/ public class Demo8 {public static void main(String[] args) {List<Integer> list = Arrays.asList(1,2,3,4,5,6);Demo8 demo = new Demo8();int result = demo.add(list);System.out.println("計算后的結果為"+result);}public int add(List<Integer> list) {//若Lambda是串行執行,則應順序打印list.parallelStream().forEach(System.out :: println);//Lambda有stream和parallelSteam(并行)return list.parallelStream().mapToInt(i -> i).sum();} } 運行結果: 4 1 3 5 6 2 計算后的結果為21 事實證明是并行執行8、Spring實現多線程
(1)新建Maven工程導入spring相關依賴
(2)新建一個java配置類(注意需要開啟@EnableAsync注解——支持異步任務)
(3)書寫異步執行的方法類(注意方法上需要有@Async——異步方法調用)
package cn.itcats.thread;import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service;@Service public class AsyncService {@Asyncpublic void Async_A() {System.out.println("Async_A is running");}@Asyncpublic void Async_B() {System.out.println("Async_B is running");} }(4)創建運行類
package cn.itcats.thread;import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Run {public static void main(String[] args) {//構造方法傳遞Java配置類Config.classAnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);AsyncService bean = ac.getBean(AsyncService.class);bean.Async_A();bean.Async_B();} }文章轉自
總結
以上是生活随笔為你收集整理的Java创建多线程的8种代码方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: B端SaaS产品工作流程
- 下一篇: 2021年中国养老前景调查报告