Java創(chuàng)建多線程的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、實(shí)現(xiàn)Runnable接口,重寫run()
實(shí)現(xiàn)Runnable接口只是完成了線程任務(wù)的編寫
若要啟動(dòng)線程,需要new Thread(Runnable target),再有thread對(duì)象調(diào)用start()方法啟動(dòng)線程
此處我們只是重寫了Runnable接口的Run()方法,并未重寫Thread類的run(),讓我們看看Thread類run()的實(shí)現(xiàn)
本質(zhì)上也是調(diào)用了我們傳進(jìn)去的Runnale target對(duì)象的run()方法
//Thread類源碼中的run()方法
//target為Thread 成員變量中的 private Runnable target;
@Override
public void run() {
if (target != null) {
target.run();
}
}
所以第二種創(chuàng)建線程的實(shí)現(xiàn)代碼如下:
package cn.itcats.thread.Test1;
/**
* 第二種創(chuàng)建啟動(dòng)線程的方式
* 實(shí)現(xiàn)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();
}
}
實(shí)現(xiàn)Runnable接口相比第一種繼承Thread類的方式,使用了面向接口,將任務(wù)與線程進(jìn)行分離,有利于解耦
3、匿名內(nèi)部類的方式
適用于創(chuàng)建啟動(dòng)線程次數(shù)較少的環(huán)境,書寫更加簡(jiǎn)便
具體代碼實(shí)現(xiàn):
package cn.itcats.thread.Test1;
/**
* 創(chuàng)建啟動(dòng)線程的第三種方式————匿名內(nèi)部類
* @author fatah
*/
public class Demo3 {
public static void main(String[] args) {
//方式1:相當(dāng)于繼承了Thread類,作為子類重寫run()實(shí)現(xiàn)
new Thread() {
public void run() {
System.out.println("匿名內(nèi)部類創(chuàng)建線程方式1...");
};
}.start();
//方式2:實(shí)現(xiàn)Runnable,Runnable作為匿名內(nèi)部類
new Thread(new Runnable() {
public void run() {
System.out.println("匿名內(nèi)部類創(chuàng)建線程方式2...");
}
} ).start();
}
}
4、帶返回值的線程(實(shí)現(xiàn)implements Callable<返回值類型>)
以上兩種方式,都沒有返回值且都無法拋出異常。
Callable和Runnbale一樣代表著任務(wù),只是Callable接口中不是run(),而是call()方法,但兩者相似,即都表示執(zhí)行任務(wù),call()方法的返回值類型即為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> 接口
* 含返回值且可拋出異常的線程創(chuàng)建啟動(dòng)方式
* @author fatah
*/
public class Demo5 implements Callable<String>{
public String call() throws Exception {
System.out.println("正在執(zhí)行新建線程任務(wù)");
Thread.sleep(2000);
return "新建線程睡了2s后返回執(zhí)行結(jié)果";
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Demo5 d = new Demo5();
/* call()只是線程任務(wù),對(duì)線程任務(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("線程執(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)線程之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)起來比較麻煩。這里推薦一個(gè)比較優(yōu)秀的開源作業(yè)調(diào)度框架“quartz”,在后期我可能會(huì)寫一篇關(guān)于quartz的博文。
6、線程池的實(shí)現(xiàn)(java.util.concurrent.Executor接口)
降低了創(chuàng)建線程和銷毀線程時(shí)間開銷和資源浪費(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è)線程的線程池
//返回的實(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)行完畢,但程序并未停止,原因是線程池并未銷毀,若想銷毀調(diào)用threadPool.shutdown(); 注意需要把我上面的
Executor threadPool = Executors.newFixedThreadPool(10);
改為
ExecutorService threadPool = Executors.newFixedThreadPool(10);
否則無shutdown()方法
若創(chuàng)建的是CachedThreadPool則不需要指定線程數(shù)量,線程數(shù)量多少取決于線程任務(wù),不夠用則創(chuàng)建線程,夠用則回收。
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)多線程
(1)新建Maven工程導(dǎo)入spring相關(guān)依賴
(2)新建一個(gè)java配置類(注意需要開啟@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)書寫異步執(zhí)行的方法類(注意方法上需要有@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)行類
package cn.itcats.thread;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Run {
public static void main(String[] args) {
//構(gòu)造方法傳遞Java配置類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è)參考,也希望大家多多支持腳本之家。
相關(guān)文章
springboot啟動(dòng)不了也不報(bào)錯(cuò)的問題及解決
這篇文章主要介紹了springboot啟動(dòng)不了也不報(bào)錯(cuò)的問題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能的示例代碼
這篇文章主要為大家詳細(xì)介紹了如何利用springboot實(shí)現(xiàn)郵箱發(fā)送(激活碼)功能,文中的示例代碼簡(jiǎn)潔易懂,有需要的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-10-10
jenkins+maven+svn自動(dòng)部署和發(fā)布的詳細(xì)圖文教程
Jenkins是一個(gè)開源的、可擴(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問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-12-12
java向多線程中傳遞參數(shù)的三種方法詳細(xì)介紹
但在多線程的異步開發(fā)模式下,數(shù)據(jù)的傳遞和返回和同步開發(fā)模式有很大的區(qū)別。由于線程的運(yùn)行和結(jié)束是不可預(yù)料的,因此,在傳遞和返回?cái)?shù)據(jù)時(shí)就無法象函數(shù)一樣通過函數(shù)參數(shù)和return語句來返回?cái)?shù)據(jù)2012-11-11

