java創(chuàng)建線程的四種方式

Java使用Thread類代表線程,所有線程都是Thread類或其子類,Java創(chuàng)建線程的方式有4種,它們分別是:
1、繼承Thread類創(chuàng)建線程;
2、實(shí)現(xiàn)Runable接口創(chuàng)建線程(首推);
3、使用Callable和Future創(chuàng)建線程;
4、使用線程池,例如Executor框架。

注意:call()方法有返回值,run()方法沒(méi)有。

方式1:Thread

public class MyThread extends Thread {

    public void run(){
        System.out.println("線程");
    }
}

public class MainTest {

    public static void main(String[] args){
        new MyThread().start();
    }
}

方式2:Runnable

public class MyThread implements Runnable {

    public void run(){
        System.out.println("線程Runnable");
    }
}

public class MainTest {

    public static void main(String[] args){
        MyThread myThread = new MyThread();
        Thread thread = new Thread(myThread);
        thread.start();
    }
}

或者直接寫(xiě)線程的實(shí)現(xiàn)

public class MainTest {

    public static void main(String[] args){
       
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("創(chuàng)建線程方式二");
            }
        }).start();
    }
}

方式3:Callable或者Future

public class CallableTest implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        // 計(jì)算1-100的和
        int sum = 0;

        for (int i = 1; i <= 100; i++)
            sum += i;

        return sum;
    }

}

public class MainTest {

    public static void main(String[] args) {
        CallableTest cd = new CallableTest();
        // 使用Callable方式創(chuàng)建線程,需要FutureTask類的支持,用于接收運(yùn)算結(jié)果,可以使用泛型指定返回值的類型
        FutureTask<Integer> result = new FutureTask<>(cd);
        new Thread(result).start();
        int sum = 0;
        // 接收運(yùn)算結(jié)果
        // 只有當(dāng)該線程執(zhí)行完畢后才會(huì)獲取到運(yùn)算結(jié)果,等同于閉鎖的效果
        try {
            sum = result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("sum is " + sum);
    }
}

方式4:Executor框架

Executor框架包括:線程池,Executor,Executors,ExecutorService,CompletionService,F(xiàn)uture,Callable等
ExecutorService的生命周期包括三種狀態(tài):運(yùn)行、關(guān)閉、終止。創(chuàng)建后便進(jìn)入運(yùn)行狀態(tài),當(dāng)調(diào)用了shutdown()方法時(shí),便進(jìn)入關(guān)閉狀態(tài),此時(shí)意味著ExecutorService不再接受新的任務(wù),但它還在執(zhí)行已經(jīng)提交了的任務(wù),當(dāng)素有已經(jīng)提交了的任務(wù)執(zhí)行完后,便到達(dá)終止?fàn)顟B(tài)。

Executors提供了一系列工廠方法用于創(chuàng)建線程池,返回的線程池都實(shí)現(xiàn)了ExecutorService接口
1、創(chuàng)建固定數(shù)目線程的線程池

public static ExecutorService newFixedThreadPool(int nThreads)

2、創(chuàng)建可緩存的線程池

public static ExecutorService newCachedThreadPool()

3、創(chuàng)建一個(gè)單線程化的Executor

public static ExecutorService newSingleThreadExecutor()

4、創(chuàng)建一個(gè)支持定時(shí)及周期性的任務(wù)執(zhí)行的線程池,多數(shù)情況下可用來(lái)替代Timer類

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)

Executor執(zhí)行Runable任務(wù)示例:

public class MainTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
//      ExecutorService executorService = Executors.newFixedThreadPool(5);
//      ExecutorService executorService = Executors.newSingleThreadExecutor();
            for (int i = 0; i < 5; i++){
                executorService.execute(new TestRunnable());
                System.out.println("************* a" + i + " *************");
            }
            executorService.shutdown();
        }
    }

    class TestRunnable implements Runnable{
        public void run(){
            System.out.println(Thread.currentThread().getName() + "線程被調(diào)用了。");
        }
    }
public class MainTest {

    private ExecutorService pool;

    @PostConstruct
    public void init(){
        //自定義線程工廠
        pool = new ThreadPoolExecutor(5, 10, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(20),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        //線程命名
                        Thread th = new Thread(r,"threadPool"+r.hashCode());
                        return th;
                    }
                },new ThreadPoolExecutor.CallerRunsPolicy());

    }

    public void test(){
        pool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "線程被調(diào)用了。");
            }
        });
    }
    
}

Executor實(shí)現(xiàn)Callable任務(wù)示例:

public class MainTest {

    public static void main(String[] args){
        ExecutorService executorService = Executors.newCachedThreadPool();
        List<Future<String>> resultList = new ArrayList<Future<String>>();

        //創(chuàng)建10個(gè)任務(wù)并執(zhí)行
        for (int i = 0; i < 10; i++){
            //使用ExecutorService執(zhí)行Callable類型的任務(wù),并將結(jié)果保存在future變量中
            Future<String> future = executorService.submit(new TaskWithResult(i));
            //將任務(wù)執(zhí)行結(jié)果存儲(chǔ)到List中
            resultList.add(future);
        }

        //遍歷任務(wù)的結(jié)果
        for (Future<String> fs : resultList){
            try{
                while(!fs.isDone());//Future返回如果沒(méi)有完成,則一直循環(huán)等待,直到Future返回完成
                System.out.println(fs.get());     //打印各個(gè)線程(任務(wù))執(zhí)行的結(jié)果
            }catch(InterruptedException e){
                e.printStackTrace();
            }catch(ExecutionException e){
                e.printStackTrace();
            }finally{
                //啟動(dòng)一次順序關(guān)閉,執(zhí)行以前提交的任務(wù),但不接受新任務(wù)
                executorService.shutdown();
            }
        }
    }
    }

class TaskWithResult implements Callable<String>{
    private int id;

    public TaskWithResult(int id){
        this.id = id;
    }

    /**
     * 任務(wù)的具體過(guò)程,一旦任務(wù)傳給ExecutorService的submit方法,
     * 則該方法自動(dòng)在一個(gè)線程上執(zhí)行
     */
    public String call() throws Exception {
        System.out.println("call()方法被自動(dòng)調(diào)用!??!    " + Thread.currentThread().getName());
        //該返回結(jié)果將被Future的get方法得到
        return "call()方法被自動(dòng)調(diào)用,任務(wù)返回的結(jié)果是:" + id + "    " + Thread.currentThread().getName();
    }
} 

自定義線程池

自定義線程池,可以用ThreadPoolExecutor類創(chuàng)建,它有多個(gè)構(gòu)造方法來(lái)創(chuàng)建線程池,用該類很容易實(shí)現(xiàn)自定義的線程池

public class MainTest {

    public static void main(String[] args){
        //創(chuàng)建等待隊(duì)列
        BlockingQueue<Runnable> bqueue = new ArrayBlockingQueue<Runnable>(20);
        //創(chuàng)建線程池,池中保存的線程數(shù)為3,允許的最大線程數(shù)為5
        ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,50,TimeUnit.MILLISECONDS,bqueue);
        //創(chuàng)建七個(gè)任務(wù)
        Runnable t1 = new MyThread1();
        Runnable t2 = new MyThread1();
        Runnable t3 = new MyThread1();
        Runnable t4 = new MyThread1();
        Runnable t5 = new MyThread1();
        Runnable t6 = new MyThread1();
        Runnable t7 = new MyThread1();
        //每個(gè)任務(wù)會(huì)在一個(gè)線程上執(zhí)行
        pool.execute(t1);
        pool.execute(t2);
        pool.execute(t3);
        pool.execute(t4);
        pool.execute(t5);
        pool.execute(t6);
        pool.execute(t7);
        //關(guān)閉線程池
        pool.shutdown();
    }
    }

class MyThread1 implements Runnable{
    @Override
    public void run(){
        System.out.println(Thread.currentThread().getName() + "正在執(zhí)行。。。");
        try{
            Thread.sleep(100);
        }catch(InterruptedException e){
            e.printStackTrace();
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容