[JAVA]JAVA實現多線程的三種方式

一、繼承Thread類,經過start()方法調用java

public class MultiThreadByExtends extends Thread {
    @Override
    public void run() {
        print("聽歌");
    }
    public static void print(String threadName){
        while (true) {
            System.out.println("線程:"+threadName+" 輸出。。。");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        MultiThreadByExtends t1 = new MultiThreadByExtends();
        t1.start();
        print("寫代碼");
    }
}

 

輸出結果:面試

 
 

線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:聽歌 輸出。。。ide

 

因爲java單繼承的特色,這種方式侷限性很大,不能繼承其餘父類spa

 

二、實現Runable接口線程

public class MultiThreadByRunnable implements Runnable {
    @Override
    public void run() {
        print("聽歌");
    }
    public static void print(String threadName){
        while (true) {
            System.out.println("線程:"+threadName+" 輸出。。。");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        MultiThreadByRunnable tr1 = new MultiThreadByRunnable();
        //代理方式啓動
        Thread thread = new Thread(tr1);
        thread.start();
        print("寫代碼");
    }
}

輸出結果:代理

線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:聽歌 輸出。。。
線程:寫代碼 輸出。。。
線程:聽歌 輸出。。。
線程:寫代碼 輸出。。。

 

三、實現callable接口code

import java.util.concurrent.*;

public class CallableTest implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        int count = 0;
        while (true){
            System.out.println("1111");
            Thread.sleep(1000);
            count++;
            if(count >10) {
                break;
            }
        }
        return true;
    }

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

        CallableTest c = new CallableTest();
        ExecutorService es = Executors.newFixedThreadPool(1);
        Future<Boolean> res = es.submit(c);
        System.out.println(res.get());
        es.shutdownNow();
    }
}

該方式的優勢是能夠獲得線程的返回值 blog

 

平時開發中經常使用到的就是一、2兩種方式,至於第三種,屬於JUC裏面的東西,若是在面試中能答上來,對初級或中級java面試來講絕對是加分項繼承

相關文章
相關標籤/搜索