Java-多线程-Thread类-继承方式
1、常规的单线程
package cn.bruce.Thread; //如何创建和启动一个线程 //创建Thread子类对象 //子类对象调用方法start() //让线程程序执行,JVM调用线程中的run public class MoreThreadDemo { public static void main(String[] args) { long ss = System.currentTimeMillis(); SubThread st = new SubThread(); st.run();// 如果是直接调用run的话还是单线程 // st.start();
new Thread(){public void run(){System.out.println("!!!");}}.start();//也可以使用这样的匿名内部类方式开启线程
long s = System.currentTimeMillis(); long r = fun(45); long e = System.currentTimeMillis(); System.out.println("main..." + (e - s)); System.out.println(r); long ee = System.currentTimeMillis(); System.out.println("result..." + (ee - ss)); } public static long fun(long a) { if (a == 1) { return 1; } else if (a == 2) { return 1; } return fun(a - 2) + fun(a - 1); } } // 定义子类,继承Thread // 重写方法run class SubThread extends Thread { public void run() { long s1 = System.currentTimeMillis(); long r1 = fun1(45); long e1 = System.currentTimeMillis(); System.out.println("run..." + (e1 - s1)); System.out.println(r1); } public static long fun1(long a) { if (a == 1) { return 1; } else if (a == 2) { return 1; } return fun1(a - 2) + fun1(a - 1); } }
需要6874ms
2、开辟一个线程后
package cn.bruce.Thread; //如何创建和启动一个线程 //创建Thread子类对象 //子类对象调用方法start() //让线程程序执行,JVM调用线程中的run public class MoreThreadDemo { public static void main(String[] args) { long ss = System.currentTimeMillis(); SubThread st = new SubThread(); // st.run();// 如果是直接调用run的话还是单线程 st.start();//开辟线程运行 long s = System.currentTimeMillis(); long r = fun(45); long e = System.currentTimeMillis(); System.out.println("main..." + (e - s)); System.out.println(r); long ee = System.currentTimeMillis(); System.out.println("result..." + (ee - ss)); } public static long fun(long a) { if (a == 1) { return 1; } else if (a == 2) { return 1; } return fun(a - 2) + fun(a - 1); } } // 定义子类,继承Thread // 重写方法run class SubThread extends Thread { public void run() { long s1 = System.currentTimeMillis(); long r1 = fun1(45); long e1 = System.currentTimeMillis(); System.out.println("run..." + (e1 - s1)); System.out.println(r1); } public static long fun1(long a) { if (a == 1) { return 1; } else if (a == 2) { return 1; } return fun1(a - 2) + fun1(a - 1); } }
只需要4042ms了