使用多線程就是爲了充分利用cpu的資源,提高程序執行效率,當你發現一個業務邏輯執行效率特別低,耗時特別長,就可以考慮使用多線程。
package learn.test; public class TestThread { public static void main(String[] args) throws Exception { System.out.println("begin"); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(5000);//模擬業務場景 System.out.println("因爲目前我們不需要中間處理的結果,因此可以讓它在後臺執行,不阻塞主線程。"); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); System.out.println("end"); } }
運行結果:
begin
end
因爲目前我們不需要中間處理的結果,因此可以讓它在後臺執行,不阻塞主線程。