併發編程場景以及知識圖譜

爲什麼要用多線程?

  • 提升程序吞吐量
  • 充分利用CPU資源

什麼場景用多線程?

  • 有比較大或者多的任務時候,就可以使用多線程。

在Java中構建多線程。

  • Thread
  • Runable
  • Callable
public class RunableDemo implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(2000);
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("Run Runable");
    }

    public static void main(String[] args) {
        new Thread(new RunableDemo()).start();
        System.out.println("Run Main");
    }
}
輸出結果  多線程並不會阻礙主線程的運行。

Run Main
Run Runable
public class CallableDemo implements Callable<String> {
    @Override
    public String call() throws Exception {
        Thread.sleep(2000);
        return "SUCCESS";
    }

    public static void main(String[] args) throws Exception {
        //創建線程池
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        CallableDemo callableDemo = new CallableDemo();
        Future<String> result = executorService.submit(callableDemo);
        System.out.println("Run Main");
        //這裏會阻塞
        System.out.println(result.get());
        System.out.println("Run Main After Result");
        executorService.shutdown();
    }
輸出結果
Run Main
SUCCESS
Run Main After Result

線程的生命週期

    public enum State {
 
        NEW,//新創建狀態

        RUNNABLE,(就緒/運行狀態)

        BLOCKED,

        WAITING,

        TIMED_WAITING,

        TERMINATED;//結束
    }

 線程的啓動與停止

 //start方法
 public synchronized void start() {

        boolean started = false;
        try {
            start0();
            started = true;
        } finally {
            try {
                if (!started) {
                    group.threadStartFailed(this);
                }
            } catch (Throwable ignore) {
                /* do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();

  //run方法
    @Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

如何安全的停止線程?


通過標誌位去關閉線程 interrupt();

thread.interrupt();//中斷一個線程 有線程處理請求可能不終止 中斷標誌位設置爲true

thread.isInterrupted();//判斷一個線程是否中斷狀態
通過標誌位去關閉線程 interrupt();

public class InterruptDemo {

    private static int i = 0;

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

        Thread thread = new Thread(() -> {
            while (!Thread.currentThread().isInterrupted()) {
                i++;
            }
            System.out.println("Num" + i);
        });

        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupted();//終止線程
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章