Java并發(fā)編程(一)線程的各種創(chuàng)建方式

方法一:繼承Thread類,作為線程對象存在(繼承Thread對象)

public class CreatThreadDemo1 extends Thread{
    /**
     * 構(gòu)造方法: 繼承父類方法的Thread(String name);方法
     * @param name
     */
    public CreatThreadDemo1(String name){
        super(name);
    }

    @Override
    public void run() {
        while (!interrupted()){
            System.out.println(getName()+"線程執(zhí)行了...");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        CreatThreadDemo1 d1 = new CreatThreadDemo1("first");
        CreatThreadDemo1 d2 = new CreatThreadDemo1("second");

        d1.start();
        d2.start();

        d1.interrupt();  //中斷第一個線程
    }
}

常規(guī)方法,不多做介紹了,interrupted方法,是來判斷該線程是否被中斷。(終止線程不允許用stop方法,該方法不會施放占用的資源。所以我們在設(shè)計程序的時候,要按照中斷線程的思維去設(shè)計,就像上面的代碼一樣)。

讓線程等待的方法
  • Thread.sleep(200); //線程休息2ms
  • Object.wait(); //讓線程進入等待,直到調(diào)用Object的notify或者notifyAll時,線程停止休眠

方法二:實現(xiàn)runnable接口,作為線程任務(wù)存在

public class CreatThreadDemo2 implements Runnable {
    @Override
    public void run() {
        while (true){
            System.out.println("線程執(zhí)行了...");
        }
    }

    public static void main(String[] args) {
        //將線程任務(wù)傳給線程對象
        Thread thread = new Thread(new CreatThreadDemo2());
        //啟動線程
        thread.start();
    }
}

Runnable 只是來修飾線程所執(zhí)行的任務(wù),它不是一個線程對象。想要啟動Runnable對象,必須將它放到一個線程對象里。

方法三:匿名內(nèi)部類創(chuàng)建線程對象

public class CreatThreadDemo3 extends Thread{
    public static void main(String[] args) {
        //創(chuàng)建無參線程對象
        new Thread(){
            @Override
            public void run() {
                System.out.println("線程執(zhí)行了...");
            }
        }.start();
       //創(chuàng)建帶線程任務(wù)的線程對象
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("線程執(zhí)行了...");
            }
        }).start();
        //創(chuàng)建帶線程任務(wù)并且重寫run方法的線程對象
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("runnable run 線程執(zhí)行了...");
            }
        }){
            @Override
            public void run() {
                System.out.println("override run 線程執(zhí)行了...");
            }
        }.start();
    }

}

創(chuàng)建帶線程任務(wù)并且重寫run方法的線程對象中,為什么只運行了Thread的run方法。我們看看Thread類的源碼,
image.png

,我們可以看到Thread實現(xiàn)了Runnable接口,而Runnable接口里有一個run方法。
所以,我們最終調(diào)用的重寫的方法應(yīng)該是Thread類的run方法。而不是Runnable接口的run方法。

方法四:創(chuàng)建帶返回值的線程

public class CreatThreadDemo4 implements Callable {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CreatThreadDemo4 demo4 = new CreatThreadDemo4();

        FutureTask<Integer> task = new FutureTask<Integer>(demo4); //FutureTask最終實現(xiàn)的是runnable接口

        Thread thread = new Thread(task);

        thread.start();

        System.out.println("我可以在這里做點別的業(yè)務(wù)邏輯...因為FutureTask是提前完成任務(wù)");
        //拿出線程執(zhí)行的返回值
        Integer result = task.get();
        System.out.println("線程中運算的結(jié)果為:"+result);
    }

    //重寫Callable接口的call方法
    @Override
    public Object call() throws Exception {
        int result = 1;
        System.out.println("業(yè)務(wù)邏輯計算中...");
        Thread.sleep(3000);
        return result;
    }
}

Callable接口介紹:

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

返回指定泛型的call方法。然后調(diào)用FutureTask對象的get方法得道call方法的返回值。

方法五:定時器Timer

public class CreatThreadDemo5 {

    public static void main(String[] args) {
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("定時器線程執(zhí)行了...");
            }
        },0,1000);   //延遲0,周期1s

    }
}

方法六:線程池創(chuàng)建線程

public class CreatThreadDemo6 {
    public static void main(String[] args) {
        //創(chuàng)建一個具有10個線程的線程池
        ExecutorService threadPool = Executors.newFixedThreadPool(10);
        long threadpoolUseTime = System.currentTimeMillis();
        for (int i = 0;i<10;i++){
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"線程執(zhí)行了...");
                }
            });
        }
        long threadpoolUseTime1 = System.currentTimeMillis();
        System.out.println("多線程用時"+(threadpoolUseTime1-threadpoolUseTime));
        //銷毀線程池
        threadPool.shutdown();
        threadpoolUseTime = System.currentTimeMillis();
    }

}

方法七:利用java8新特性 stream 實現(xiàn)并發(fā)

lambda表達式不懂的,可以看看我的java8新特性文章:
java8-lambda:http://www.itdecent.cn/p/3a08dc78a05f
java8-stream:http://www.itdecent.cn/p/ea16d6712a00

public class CreatThreadDemo7 {
    public static void main(String[] args) {
        List<Integer> values = Arrays.asList(10,20,30,40);
        //parallel 平行的,并行的
        int result = values.parallelStream().mapToInt(p -> p*2).sum();
        System.out.println(result);
        //怎么證明它是并發(fā)處理呢
        values.parallelStream().forEach(p-> System.out.println(p));
    }
}

200
40
10
20
30

怎么證明它是并發(fā)處理呢,他們并不是按照順序輸出的 。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,500評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,612評論 18 399
  • 題目LINK 題意解釋 這道題是給出了3個值的任意兩個值,求剩下的那個。題中給出了公式,所以直接自己反推下公式就好...
    DeamoV閱讀 331評論 0 0
  • (本文參考課本是《HTTP權(quán)威指南》,文中的書寫結(jié)構(gòu)是根據(jù)自己的閱讀理解的個人思路,如有不懂可以自行參考原書) 第...
    Andrew_bao閱讀 668評論 1 3

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