现在个人电脑以及服务器都是多核cpu,如何提高多核cpu的利用率,就要用到多线程技术了。
public class TestThread1 { static int i = 0; static class PThread extends Thread { public void run() { for (int j = 1; j < 900000000; j++) { i=i-1; System.out.println(i); } } } static class AThread extends Thread { public void run() { for (int j = 1; j < 900000000; j++) { i=i+1; System.out.println(i); } } } public static void main(String[] args) { // TODO Auto-generated method stub PThread p1 = new PThread(); AThread p2 = new AThread(); PThread p3 = new PThread(); AThread p4 = new AThread(); // PThread p5 = new PThread(); // PThread p6 = new PThread(); // PThread p7 = new PThread(); // PThread p8 = new PThread(); p1.start(); p2.start(); p3.start(); p4.start(); // p5.start(); // p6.start(); // p7.start(); // p8.start(); } }
一个线程的时候本地cpu占到:
两个或者多个的时候: