創建多線程的4種方式


- 繼承Thread

繼承Thread類,重寫run方法實現多線程

package com.noneplus;

class Task1 extends Thread {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("Task1輸出:" + i);
        }
    }
}

class Task2 extends Thread {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("                 Task2輸出:" + i);
        }
    }
}

/**
 * @Description: 繼承Thread,重寫run方法,實現多線程
 * @Author noneplus
 * @Date 2020/8/3 17:34
 */
public class ExtendThread {

    public static void main(String[] args) {

        Task1 task1 = new Task1();
        task1.start();

        Task2 task2 = new Task2();
        task2.start();

        for (int i = 0; i < 10; i++) {
            System.out.println("                                         mainTask輸出:" + i);
        }

        //3個線程的執行順序由CPU的線程調度決定

    }
}

- 實現Runnable接口

Runnable接口解決了單繼承的問題

package com.noneplus;

class Task3 implements Runnable {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("Task1輸出:" + i);
        }
    }
}

class Task4 implements Runnable {

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("                      Task2輸出:" + i);
        }
    }
}

/**
 * @Description: 實現Runnable接口,實現多線程,彌補單繼承的問題
 * @Author noneplus
 * @Date 2020/8/3 17:34
 */
public class ImplementRunnable {

    public static void main(String[] args) {

        Task3 runnable3 = new Task3();
        Task4 runnable4 = new Task4();

        Thread task3 = new Thread(runnable3);
        Thread task4 = new Thread(runnable4);

        task3.start();
        task4.start();

        for (int i = 0; i < 10; i++) {
            System.out.println("                                                                  " +
                    " mainTask輸出:" + i);
        }

        //3個線程的執行順序由CPU的線程調度決定

    }
}

- 實現Callable接口

Callable支持返回值(但用多線程加返回值有點奇怪)

package com.noneplus;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

class Task5 implements Callable {

    @Override
    public Integer call() throws Exception {
        Integer i = 0;
        for (; i < 10; i++) {
            System.out.println("Task5輸出:" + i);
        }
        return i;
    }
}

class Task6 implements Callable {

    @Override
    public Integer call() throws Exception {
        Integer i = 0;
        for (; i < 10; i++) {
            System.out.println("             Task6輸出:" + i);
        }
        return i;
    }
}


/**
 * @Description: 實現Callable接口,可以定義返回值
 * @Author noneplus
 * @Date 2020/8/3 17:53
 */
public class ImplementCallable {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        for (int i = 0; i < 10; i++) {
            System.out.println("                                         mainTask輸出:" + i);
        }

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new Task5());
        FutureTask<Integer> futureTask1 = new FutureTask<Integer>(new Task6());

        Thread thread = new Thread(futureTask);
        Thread thread1 = new Thread(futureTask1);

        thread.start();
        thread1.start();

        System.out.println("任務返回結果:"+futureTask.get());
        System.out.println("任務返回結果:"+futureTask1.get());

    }
}

- 使用線程池ThreadPoolExecutor

package com.noneplus;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

class Task7 implements Runnable {
    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("Task7輸出:" + i + "當前線程" + Thread.currentThread().getName());
        }
    }
}

class Task8 implements Runnable {
    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            System.out.println("Task8輸出:" + i + "當前線程" + Thread.currentThread().getName());

        }

    }
}

/**
 * @Description: 使用線程池創建線程池,實現線程復用和管理
 * @Author noneplus
 * @Date 2020/8/5 15:38
 */
public class ThreadPool {

    public static void main(String[] args) {
        /**
         * 阿里推薦:ThreadPoolExecutor
         * ```
         * public ThreadPoolExecutor(int corePoolSize,
         *                               int maximumPoolSize,
         *                               long keepAliveTime,
         *                               TimeUnit unit,
         *                               BlockingQueue<Runnable> workQueue)
         * ```
         * 1、corePoolSize 核心線程數大小,當線程數 < corePoolSize ,會創建線程執行 runnable
         *
         * 2、maximumPoolSize 最大線程數, 當線程數 >= corePoolSize的時候,會把 runnable 放入 workQueue中
         *
         * 3、keepAliveTime 保持存活時間,當線程數大於corePoolSize的空閑線程能保持的最大時間。
         *
         * 4、unit 時間單位
         *
         * 5、workQueue 保存任務的阻塞隊列
         *
         * 6、threadFactory 創建線程的工廠
         *
         * 7、handler 拒絕策略
         *
         */
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 10, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3));

        for (int i=0;i<10;i++)
        {
            threadPoolExecutor.execute(new Task7());

            threadPoolExecutor.execute(new Task8());
        }


    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM