首頁 > Java > Java入門 > 主體

關於java中創建線程的方式的總結

王林
發布: 2020-01-08 16:59:06
轉載
2157 人瀏覽過

關於java中創建線程的方式的總結

1、繼承Thread類別

public class ThreadCreator extends Thread{

    public static void main(String[] args) {
       //第一种方式:
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
       //第二种方式:
       Thread thread = new ThreadCreator();
       thread.start();
       //第三种方式:
       new ThreadCreator().start();
   }
 
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}
登入後複製

2、實作Runnable介面

(免費學習影片教學分享:java影片教學

public class ThreadCreator implements Runnable{

    public static void main(String[] args) {
       ThreadCreator creator = new ThreadCreator();
       Thread thread = new Thread(creator,"线程1");
       thread.start();
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "run");
    }
}
登入後複製

3、實作Callable介面

public class ThreadCreator implements Callable<Integer> {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
       ThreadCreator creator = new ThreadCreator();
       FutureTask futureTask = new FutureTask(creator);
       Thread thread = new Thread(futureTask,"线程");
       thread.start();
       System.out.println(futureTask.get());
    }

    @Override
    public Integer call() {
        return 1024;
    }
}
登入後複製

4、執行緒池ExecutorService

public class ThreadCreator{

   static ExecutorService service = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //execute无返回值
        service.execute(new ThreadTask(1,"1"));
        //submit有返回值
        Future<Integer> result = service.submit(new ThreadTaskCall());
        System.out.println(result.get());
        service.shutdownNow();
    }
    static class ThreadTask implements Runnable{
        private int param1;
        private String param2;
        public ThreadTask(int param3,String param4){
            this.param1 = param3;
            this.param2 = param4;
        }
        @Override
        public void run() {
            System.out.println(param1+param2);
        }
    }

    static class ThreadTaskCall implements Callable<Integer>{
        @Override
        public Integer call() throws Exception {
            return 1024;
        }
    }
}
登入後複製

執行緒池中submit和execute的區別:

(1 )可接受的任務類型不一樣:execute只能接受Runnable任務,submit還可以接受Callable任務。

(2)回傳值:execute無回傳值,任務一旦提交,無法在目前執行緒中監控執行結果。 submit有一個Future類型的回傳值,用來接收回傳值或回應異常。透過get()方法取得。

submit底層還是呼叫的execute,只是在此基礎上用future封裝了一層,並將執行過程中產生的異常全部封裝在一個變數中:

public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);
            }
        } finally {
            runner = null;
            int s = state;
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }
protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }
登入後複製

另外,spring中的schedule註解借鏡使用了submit的處理方式。

5、匿名內部類別

public class ThreadCreator {

    public static void main(String[] args) {

        //继承Thread类
        new Thread() {
            @Override
            public void run() {
                System.out.println("extends Thread Class!");
            }
        }.start();
        //实现Runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("implement Runnable!");
            }
        }).start();
        //实现Callable接口
        new Thread(new FutureTask<Integer>(new Callable() {
            @Override
            public Integer call() throws Exception {
                return 1024;
            }
        })).start();
        //lambda表达式
        new Thread(() -> System.out.println("execute single code")).start();
        new Thread(() -> {
            System.out.println("execute multiple code");
        }).start();
    }
}
登入後複製

lambda執行緒池:

public class ThreadCreator {

    static ExecutorService service = Executors.newFixedThreadPool(5);

    static List list = new ArrayList();

    public static void main(String[] args) {
        service.execute(() -> execute()); //无返回值
        Future future = service.submit(() -> execute()); //有返回值
        list.add(future);
    }

    public static void execute() {
        //do something
    }
}
登入後複製

推薦相關文章教學:java快速入門

以上是關於java中創建線程的方式的總結的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:cnblogs.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板