Java創(chuàng)建多線(xiàn)程的8種方式集合
1、繼承Thread類(lèi),重寫(xiě)run()方法
//方式1
package cn.itcats.thread.Test1;
public class Demo1 extends Thread{
//重寫(xiě)的是父類(lèi)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、實(shí)現(xiàn)Runnable接口,重寫(xiě)run()
實(shí)現(xiàn)Runnable接口只是完成了線(xiàn)程任務(wù)的編寫(xiě)
若要啟動(dòng)線(xiàn)程,需要new Thread(Runnable target),再有thread對(duì)象調(diào)用start()方法啟動(dòng)線(xiàn)程
此處我們只是重寫(xiě)了Runnable接口的Run()方法,并未重寫(xiě)Thread類(lèi)的run(),讓我們看看Thread類(lèi)run()的實(shí)現(xiàn)
本質(zhì)上也是調(diào)用了我們傳進(jìn)去的Runnale target對(duì)象的run()方法
//Thread類(lèi)源碼中的run()方法
//target為T(mén)hread 成員變量中的 private Runnable target;
@Override
public void run() {
if (target != null) {
target.run();
}
}
所以第二種創(chuàng)建線(xiàn)程的實(shí)現(xiàn)代碼如下:
package cn.itcats.thread.Test1;
/**
* 第二種創(chuàng)建啟動(dòng)線(xiàn)程的方式
* 實(shí)現(xiàn)Runnale接口
* @author fatah
*/
public class Demo2 implements Runnable{
//重寫(xiě)的是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();
}
}
實(shí)現(xiàn)Runnable接口相比第一種繼承Thread類(lèi)的方式,使用了面向接口,將任務(wù)與線(xiàn)程進(jìn)行分離,有利于解耦
3、匿名內(nèi)部類(lèi)的方式
適用于創(chuàng)建啟動(dòng)線(xiàn)程次數(shù)較少的環(huán)境,書(shū)寫(xiě)更加簡(jiǎn)便
具體代碼實(shí)現(xiàn):
package cn.itcats.thread.Test1;
/**
* 創(chuàng)建啟動(dòng)線(xiàn)程的第三種方式————匿名內(nèi)部類(lèi)
* @author fatah
*/
public class Demo3 {
public static void main(String[] args) {
//方式1:相當(dāng)于繼承了Thread類(lèi),作為子類(lèi)重寫(xiě)run()實(shí)現(xiàn)
new Thread() {
public void run() {
System.out.println("匿名內(nèi)部類(lèi)創(chuàng)建線(xiàn)程方式1...");
};
}.start();
//方式2:實(shí)現(xiàn)Runnable,Runnable作為匿名內(nèi)部類(lèi)
new Thread(new Runnable() {
public void run() {
System.out.println("匿名內(nèi)部類(lèi)創(chuàng)建線(xiàn)程方式2...");
}
} ).start();
}
}
4、帶返回值的線(xiàn)程(實(shí)現(xiàn)implements Callable<返回值類(lèi)型>)
以上兩種方式,都沒(méi)有返回值且都無(wú)法拋出異常。
Callable和Runnbale一樣代表著任務(wù),只是Callable接口中不是run(),而是call()方法,但兩者相似,即都表示執(zhí)行任務(wù),call()方法的返回值類(lèi)型即為Callable接口的泛型
具體代碼實(shí)現(xiàn):
package cn.itcats.thread.Test1;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
/**
* 方式4:實(shí)現(xiàn)Callable<T> 接口
* 含返回值且可拋出異常的線(xiàn)程創(chuàng)建啟動(dòng)方式
* @author fatah
*/
public class Demo5 implements Callable<String>{
public String call() throws Exception {
System.out.println("正在執(zhí)行新建線(xiàn)程任務(wù)");
Thread.sleep(2000);
return "新建線(xiàn)程睡了2s后返回執(zhí)行結(jié)果";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Demo5 d = new Demo5();
/* call()只是線(xiàn)程任務(wù),對(duì)線(xiàn)程任務(wù)進(jìn)行封裝
class FutureTask<V> implements RunnableFuture<V>
interface RunnableFuture<V> extends Runnable, Future<V>
*/
FutureTask<String> task = new FutureTask<>(d);
Thread t = new Thread(task);
t.start();
System.out.println("提前完成任務(wù)...");
//獲取任務(wù)執(zhí)行后返回的結(jié)果
String result = task.get();
System.out.println("線(xiàn)程執(zhí)行結(jié)果為"+result);
}
}
5、定時(shí)器(java.util.Timer)
關(guān)于Timmer的幾個(gè)構(gòu)造方法

執(zhí)行定時(shí)器任務(wù)使用的是schedule方法:

具體代碼實(shí)現(xiàn):
package cn.itcats.thread.Test1;
import java.util.Timer;
import java.util.TimerTask;
/**
* 方法5:創(chuàng)建啟動(dòng)線(xiàn)程之Timer定時(shí)任務(wù)
* @author fatah
*/
public class Demo6 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("定時(shí)任務(wù)延遲0(即立刻執(zhí)行),每隔1000ms執(zhí)行一次");
}
}, 0, 1000);
}
}
我們發(fā)現(xiàn)Timer有不可控的缺點(diǎn),當(dāng)任務(wù)未執(zhí)行完畢或我們每次想執(zhí)行不同任務(wù)時(shí)候,實(shí)現(xiàn)起來(lái)比較麻煩。這里推薦一個(gè)比較優(yōu)秀的開(kāi)源作業(yè)調(diào)度框架“quartz”,在后期我可能會(huì)寫(xiě)一篇關(guān)于quartz的博文。
6、線(xiàn)程池的實(shí)現(xiàn)(java.util.concurrent.Executor接口)
降低了創(chuàng)建線(xiàn)程和銷(xiāo)毀線(xiàn)程時(shí)間開(kāi)銷(xiāo)和資源浪費(fèi)
具體代碼實(shí)現(xiàn):
package cn.itcats.thread.Test1;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class Demo7 {
public static void main(String[] args) {
//創(chuàng)建帶有5個(gè)線(xiàn)程的線(xiàn)程池
//返回的實(shí)際上是ExecutorService,而ExecutorService是Executor的子接口
Executor threadPool = Executors.newFixedThreadPool(5);
for(int i = 0 ;i < 10 ; i++) {
threadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName()+" is running");
}
});
}
}
}
運(yùn)行結(jié)果:
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-3 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-5 is running
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
運(yùn)行完畢,但程序并未停止,原因是線(xiàn)程池并未銷(xiāo)毀,若想銷(xiāo)毀調(diào)用threadPool.shutdown(); 注意需要把我上面的
Executor threadPool = Executors.newFixedThreadPool(10);
改為
ExecutorService threadPool = Executors.newFixedThreadPool(10);
否則無(wú)shutdown()方法
若創(chuàng)建的是CachedThreadPool則不需要指定線(xiàn)程數(shù)量,線(xiàn)程數(shù)量多少取決于線(xiàn)程任務(wù),不夠用則創(chuàng)建線(xiàn)程,夠用則回收。
7、Lambda表達(dá)式的實(shí)現(xiàn)(parallelStream)
package cn.itcats.thread.Test1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 使用Lambda表達(dá)式并行計(jì)算
* 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("計(jì)算后的結(jié)果為"+result);
}
public int add(List<Integer> list) {
//若Lambda是串行執(zhí)行,則應(yīng)順序打印
list.parallelStream().forEach(System.out :: println);
//Lambda有stream和parallelSteam(并行)
return list.parallelStream().mapToInt(i -> i).sum();
}
}
運(yùn)行結(jié)果:
4
1
3
5
6
2計(jì)算后的結(jié)果為21
事實(shí)證明是并行執(zhí)行
8、Spring實(shí)現(xiàn)多線(xiàn)程
(1)新建Maven工程導(dǎo)入spring相關(guān)依賴(lài)
(2)新建一個(gè)java配置類(lèi)(注意需要開(kāi)啟@EnableAsync注解——支持異步任務(wù))
package cn.itcats.thread;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@ComponentScan("cn.itcats.thread")
@EnableAsync
public class Config {
}
(3)書(shū)寫(xiě)異步執(zhí)行的方法類(lèi)(注意方法上需要有@Async——異步方法調(diào)用)
package cn.itcats.thread;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncService {
@Async
public void Async_A() {
System.out.println("Async_A is running");
}
@Async
public void Async_B() {
System.out.println("Async_B is running");
}
}
(4)創(chuàng)建運(yùn)行類(lèi)
package cn.itcats.thread;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Run {
public static void main(String[] args) {
//構(gòu)造方法傳遞Java配置類(lèi)Config.class
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
AsyncService bean = ac.getBean(AsyncService.class);
bean.Async_A();
bean.Async_B();
}
}
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- Java線(xiàn)程創(chuàng)建的四種方式總結(jié)
- java中線(xiàn)程池最實(shí)用的創(chuàng)建與關(guān)閉指南
- 如何在Java中創(chuàng)建線(xiàn)程通信的四種方式你知道嗎
- Java基礎(chǔ)之多線(xiàn)程方法狀態(tài)和創(chuàng)建方法
- Java創(chuàng)建線(xiàn)程及配合使用Lambda方式
- java實(shí)現(xiàn)/創(chuàng)建線(xiàn)程的幾種方式小結(jié)
- 很多人竟然不知道Java線(xiàn)程池的創(chuàng)建方式有7種
- Java線(xiàn)程的三種創(chuàng)建方式
相關(guān)文章
springboot啟動(dòng)不了也不報(bào)錯(cuò)的問(wèn)題及解決
這篇文章主要介紹了springboot啟動(dòng)不了也不報(bào)錯(cuò)的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10
IntelliJ IDEA查看方法說(shuō)明文檔的圖解
今天小編就為大家分享一篇關(guān)于IntelliJ IDEA查看方法說(shuō)明文檔的圖解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10
jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程
Jenkins是一個(gè)開(kāi)源的、可擴(kuò)展的持續(xù)集成、交付、部署的基于web界面的平臺(tái)。這篇文章主要介紹了jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程,需要的朋友可以參考下2020-09-09
java 中序列化與readResolve()方法的實(shí)例詳解
這篇文章主要介紹了java 中序列化與readResolve()方法的實(shí)例詳解的相關(guān)資料,這里提供實(shí)例幫助大家理解這部分知識(shí),需要的朋友可以參考下2017-08-08
如何解決java.lang.ClassNotFoundException: com.mysql.jdbc.Dr
這篇文章主要介紹了如何解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
一篇文章弄懂JVM類(lèi)加載機(jī)制過(guò)程以及原理
JVM原理對(duì)于初學(xué)者而言,比較晦澀難以理解,概念繁多又比較抽象,很多時(shí)候感覺(jué)看不見(jiàn)摸不著,還不好驗(yàn)證,下面這篇文章主要給大家介紹了關(guān)于如何通過(guò)一篇文章弄懂JVM類(lèi)加載機(jī)制過(guò)程及原理的相關(guān)資料,需要的朋友可以參考下2023-02-02
java向多線(xiàn)程中傳遞參數(shù)的三種方法詳細(xì)介紹
但在多線(xiàn)程的異步開(kāi)發(fā)模式下,數(shù)據(jù)的傳遞和返回和同步開(kāi)發(fā)模式有很大的區(qū)別。由于線(xiàn)程的運(yùn)行和結(jié)束是不可預(yù)料的,因此,在傳遞和返回?cái)?shù)據(jù)時(shí)就無(wú)法象函數(shù)一樣通過(guò)函數(shù)參數(shù)和return語(yǔ)句來(lái)返回?cái)?shù)據(jù)2012-11-11

