java 創(chuàng)建線(xiàn)程的四種方式
1、繼承Thread類(lèi)方式
這種方式適用于執(zhí)行特定任務(wù),并且需要獲取處理后的數(shù)據(jù)的場(chǎng)景。
舉例:一個(gè)用于累加數(shù)組內(nèi)數(shù)據(jù)的和的線(xiàn)程。
public class AdditionThread extends Thread {
private int sum = 0;
private int[] nums;
public AdditionThread(int[] nums, String threadName) {
super(threadName);
this.nums = nums;
}
@Override
public void run() {
for (int num : nums) {
sum += num;
}
}
public int getSum() {
return sum;
}
}
調(diào)用方式:
public class Main {
public static void main(String[] args) throws InterruptedException {
int[] nums = {10, 12, 15, 200, 100};
AdditionThread thread = new AdditionThread(nums, "AdditionThread");
thread.start();
thread.join();
System.out.println("sum=" + thread.getSum());
}
}
2、Runnable 接口方式
定義一個(gè)實(shí)現(xiàn)Runnable接口的類(lèi),或者直接創(chuàng)建一個(gè)匿名內(nèi)部類(lèi),并覆蓋 run() 方法。最后作為參數(shù)傳給Thread的構(gòu)造函數(shù)。
public class Main {
public static void main(String[] args) {
// 自定義的 Runnable
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable, "Runnable-Thread");
thread.start();
// 自定義匿名內(nèi)部類(lèi)
new Thread(() -> {
System.out.println("Inner class");
}).start();
}
static class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("MyRunnable");
}
}
}
3、 Callable 接口方式
Callable 接口與 Runnable 接口的區(qū)別:
(1)Callable 的方法為call(),Runnable的方法為run()。
(2)Callable 的方法由返回值,Runnable 沒(méi)有。
(3)Callable 的方法聲明的Exception,Runnable的沒(méi)有。
public class Main {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask<String> task = new FutureTask<>(myCallable);
Thread thread = new Thread(task, "FutureTask");
thread.start();
try {
// 通過(guò)get方法獲取返回值
String result = task.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
static class MyCallable implements Callable<String> {
@Override
public String call() throws Exception {
// 模擬超時(shí)操作
Thread.sleep(1000);
return "OK";
}
}
}
4、線(xiàn)程池方式
我們可以通過(guò) ThreadPoolExecutor 類(lèi)的構(gòu)造函數(shù)來(lái)創(chuàng)建線(xiàn)程池,也可以通過(guò)Executors工廠(chǎng)方法來(lái)創(chuàng)建,如
// 創(chuàng)建固定線(xiàn)程數(shù)的線(xiàn)程池 Executors.newFixedThreadPool(); // 創(chuàng)建只有一個(gè)核心線(xiàn)程的線(xiàn)程池 Executors.newSingleThreadExecutor(); // 創(chuàng)建一個(gè)沒(méi)有核心線(xiàn)程,但可以緩存線(xiàn)程的線(xiàn)程池 Executors.newCachedThreadPool(); // 創(chuàng)建一個(gè)適用于執(zhí)行定時(shí)任務(wù)的線(xiàn)程池 Executors.newScheduledThreadPool();
在創(chuàng)建線(xiàn)程池時(shí),最好傳入 ThreadFactory 參數(shù),指定線(xiàn)程池所創(chuàng)建線(xiàn)程的名稱(chēng)。這樣有利于分析定位可能存在的問(wèn)題。
public class Main {
private static final ExecutorService SERVICE =
Executors.newFixedThreadPool(5, new BasicThreadFactory("My-Thread"));
public static void main(String[] args) {
// 打印線(xiàn)程的名字
System.out.println("main thread name:" + Thread.currentThread().getName());
SERVICE.execute(() -> {
System.out.println("Hello thread pool.");
// 打印線(xiàn)程池里的線(xiàn)程的名字
System.out.println("thread name:" + Thread.currentThread().getName());
});
}
static class BasicThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(0);
private final String basicName;
public BasicThreadFactory(String basicName) {
this.basicName = basicName;
}
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
String name = this.basicName + "-" + threadNumber.incrementAndGet();
thread.setName(name);
return thread;
}
}
}
以上就是java 創(chuàng)建線(xiàn)程的四種方式的詳細(xì)內(nèi)容,更多關(guān)于java 創(chuàng)建線(xiàn)程的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Callable實(shí)現(xiàn)多線(xiàn)程步驟詳解
這篇文章主要介紹了Callable實(shí)現(xiàn)多線(xiàn)程步驟詳解,Callable是一個(gè)接口,用于實(shí)現(xiàn)多線(xiàn)程,與實(shí)現(xiàn)Runnable類(lèi)似,但是功能更強(qiáng)大,該方法可以在任務(wù)結(jié)束后提供一個(gè)返回值,需要的朋友可以參考下2023-10-10
java多媒體文件編碼 處理工具類(lèi)代碼實(shí)例
這篇文章主要介紹了java多媒體文件編碼 處理工具類(lèi)使用解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
Springboot ApplicationRunner的使用解讀
這篇文章主要介紹了Springboot ApplicationRunner的使用解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
JNDI在JavaEE中的角色_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要介紹了JNDI在JavaEE中的角色,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-08-08
Java實(shí)現(xiàn)對(duì)象按照其屬性排序的兩種方法示例
這篇文章主要介紹了Java實(shí)現(xiàn)對(duì)象按照其屬性排序的兩種方法,結(jié)合實(shí)例形式詳細(xì)分析了Java對(duì)象按照其屬性排序的兩種實(shí)現(xiàn)方法與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-05-05
Spring Boot啟動(dòng)時(shí)調(diào)用自己的非web邏輯
在spring Boot中,有些代碼是WEB功能,例如API等,但是有些邏輯是非WEB,啟動(dòng)時(shí)就要調(diào)用并持續(xù)運(yùn)行的,該如何加載自己的非WEB邏輯呢,下面通過(guò)實(shí)例代碼給大家講解,一起看看吧2017-07-07
Java 集合中的類(lèi)關(guān)于線(xiàn)程安全
這篇文章主要介紹了Java 集合中的類(lèi)關(guān)于線(xiàn)程安全的相關(guān)資料,需要的朋友可以參考下2017-01-01
idea中同一SpringBoot項(xiàng)目多端口啟動(dòng)
本文主要介紹了idea中同一SpringBoot項(xiàng)目多端口啟動(dòng),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-04-04

