1、直接上代碼一看明白:
package multithreadingTest;
class fblib extends Thread{
public static Integer fb(Integer n){
return n<2?1:fb(n-1)+fb(n-2);
}
public static void bl1(int n) throws InterruptedException {
for (int i=0;i<n;i++){
System.out.println("fblib:"+i);
Thread.sleep(500);
}
}
@Override
public void run() {
super.run();
try {
bl1(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//System.out.println(fb(40));
}
}
class countl extends Thread{
public static void bl(int n) throws InterruptedException {
for (int i=0;i<n;i++){
System.out.println("count1:"+i);
Thread.sleep(500);
}
}
@Override
public void run() {
super.run();
try {
bl(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class mutithDemo{
public mutithDemo(){}
public static void main(String[] args) throws InterruptedException {
// 1、不采用多線程進行並發執行
System.out.println("-----不采用多線程執行任務---------");
long startTime = System.currentTimeMillis();
fblib.bl1(10);
countl.bl(10);
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
// 2、采用多線進行並發任務執行
System.out.println("-----采用多線程執行任務實現並發---------");
long startTime1 = System.currentTimeMillis();
fblib f1 = new fblib();
countl f2 = new countl();
//開啟兩個線程執行兩個任務
f1.start();
f2.start();
//等待這兩個線程執行結束后在執行以下代碼。
f1.join();
f2.join();
long endTime1 = System.currentTimeMillis();
System.out.println(endTime1-startTime1);
}
}