使用多线程就是为了充分利用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
因为目前我们不需要中间处理的结果,因此可以让它在后台执行,不阻塞主线程。