Java多線程系列詳解_01_線程的創建和啓動

線程的釋義(What)

百度百科如下:

在這裏插入圖片描述

爲什麼要有線程(Why)

  在Java中很多文件IO操作和網絡IO操作都是比較耗時的,比如下載10個文件到本地,這時一般的程序會一個一個
文件的下載,加入使用多線程操作會將10個文件同時下載,這個時候會節省好多時間.
  本文的例子是讀取數據庫內容並寫入本地文件,話不多說,讓我們一起看代碼吧! 

線程的創建方式(How)

  1. 未使用多線程之前
/**
 * @author alone
 * @date 2020/5/12
 */
 public static void main(String[] args) {
        readFromDataBase();
        writeDataToFile();
    }

    private static void readFromDataBase() {
        //read data from database and handle it.
        try {
            println("Begin read data from db.");
            Thread.sleep(30_000);
            println("Read data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        println("The data handle finish and successfully.");
    }

    private static void writeDataToFile() {
        try {
            println("Begin write data to file.");
            Thread.sleep(20_000);
            println("Write data done and start handle it.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        println("The data handle finish and successfully.");
    }
    
    private static void println(String message) {
        System.out.println(message);
    }
  1. 使用Thread類創建線程
public static void main(String[] args) {
//        readFromDataBase();
//        writeDataToFile();
        Thread thread1 = new Thread(){
            @Override
            public void run() {
                readFromDataBase();
            }
        };
        Thread thread2 = new Thread(){
            @Override
            public void run() {
                writeDataToFile();
            }
        };
        thread1.start();
        thread2.start();
    }

  1. 使用Runnable接口創建線程
public static void main(String[] args) {
//        readFromDataBase();
//        writeDataToFile();
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                readFromDataBase();
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                writeDataToFile();
            }
        });
        thread1.start();
        thread2.start();
    }

在這裏插入圖片描述
通過上圖源碼看出Runable接口是一個函數式接口,所以使用Java8 Lamda表達式改造如下

public static void main(String[] args) {
//        readFromDataBase();
//        writeDataToFile();
        new Thread(()->readFromDataBase()).start();
        new Thread(()->writeDataToFile()).start();
    }

線程的啓動

  我們看到線程的啓動方法使用的是Thread類的start()方法,並不是直接調用run()方法,這裏的原因如下:
    如果直接調用run方法的話 只是方法之間的調用,並不會創建線程,我們可以通過閱讀源碼的方式看到.
    調用start()方法底層其實是調用了JNI  C++的底層方法

在這裏插入圖片描述
在這裏插入圖片描述

線程的生命週期

本圖片來自線程的生命週期,瞭解詳細生命週期的變化請移步前文連接.

線程的生命週期是由下列狀態組成:

  • new(新建狀態)
  • Runable(就緒狀態)
  • Running(運行狀態)
  • Block(阻塞狀態)
  • Dead活Terminate(死亡狀態)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章