java 創(chuàng)建線程的四種方式
1、繼承Thread類方式
這種方式適用于執(zhí)行特定任務(wù),并且需要獲取處理后的數(shù)據(jù)的場景。
舉例:一個用于累加數(shù)組內(nèi)數(shù)據(jù)的和的線程。
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 接口方式
定義一個實現(xiàn)Runnable接口的類,或者直接創(chuàng)建一個匿名內(nè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)部類 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 沒有。
(3)Callable 的方法聲明的Exception,Runnable的沒有。
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 { // 通過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 { // 模擬超時操作 Thread.sleep(1000); return 'OK'; } }}
4、線程池方式
我們可以通過 ThreadPoolExecutor 類的構(gòu)造函數(shù)來創(chuàng)建線程池,也可以通過Executors工廠方法來創(chuàng)建,如
// 創(chuàng)建固定線程數(shù)的線程池Executors.newFixedThreadPool(); // 創(chuàng)建只有一個核心線程的線程池Executors.newSingleThreadExecutor();// 創(chuàng)建一個沒有核心線程,但可以緩存線程的線程池Executors.newCachedThreadPool();// 創(chuàng)建一個適用于執(zhí)行定時任務(wù)的線程池Executors.newScheduledThreadPool();
在創(chuàng)建線程池時,最好傳入 ThreadFactory 參數(shù),指定線程池所創(chuàng)建線程的名稱。這樣有利于分析定位可能存在的問題。
public class Main { private static final ExecutorService SERVICE = Executors.newFixedThreadPool(5, new BasicThreadFactory('My-Thread')); public static void main(String[] args) { // 打印線程的名字 System.out.println('main thread name:' + Thread.currentThread().getName()); SERVICE.execute(() -> { System.out.println('Hello thread pool.'); // 打印線程池里的線程的名字 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)建線程的四種方式的詳細內(nèi)容,更多關(guān)于java 創(chuàng)建線程的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. vue實現(xiàn)web在線聊天功能2. JavaScript實現(xiàn)頁面動態(tài)驗證碼的實現(xiàn)示例3. JavaEE SpringMyBatis是什么? 它和Hibernate的區(qū)別及如何配置MyBatis4. Springboot 全局日期格式化處理的實現(xiàn)5. SpringBoot+TestNG單元測試的實現(xiàn)6. 完美解決vue 中多個echarts圖表自適應(yīng)的問題7. 解決Android Studio 格式化 Format代碼快捷鍵問題8. 在Chrome DevTools中調(diào)試JavaScript的實現(xiàn)9. Python使用urlretrieve實現(xiàn)直接遠程下載圖片的示例代碼10. Java使用Tesseract-Ocr識別數(shù)字
