簡述:
1. 簡單用一下Java的多線程的兩種粗略的實現方法
繼承Thread和實現Runnable介面
實現:
1. 隨機給一個自然數n, 分發給多個線程, 每個線程計算n項的Fibonacci數列的和,計算完成後輸出,
1)繼承Thread類實現,並重寫run()方法
package test.multithread.Fibonacci;import java.util.Random;public class TestA_1 extends Thread{private int n;private static int taskCount = 0;private final int id = taskCount++;public TestA_1(int n) {this.n = n;}public static void main(String[] args){for(int i = 0;i < 10;i++){Random random = new Random(); Integer x = random.nextInt(100);new TestA_1(x).start();}}@Override//run implement the counting of different n public void run() {int sum = 0;if(n == 0 || n == 1){sum += n;}else{sum = 1;for(int i = 1;i < n;i++){sum += i;}}System.out.println("id: " + id + ",\t" + n + ": " + sum);Thread.yield(); // now the CPU could transfer the thread to a new Thread}}
2)實現Runnable介面中run方法
package test.multithread.Fibonacci;import java.util.Random;public class TestA_2 implements Runnable{private int n;private static int taskCount = 0;private final int id = taskCount++;public TestA_2(int n) {this.n = n;}public static void main(String[] args){for(int i = 0;i < 10;i++){Random random = new Random(); Integer x = random.nextInt(100);new TestA_2(x).run();}}@Override//run implement the counting of different n public void run() {int sum = 0;if(n == 0 || n == 1){sum += n;}else{sum = 1;for(int i = 1;i < n;i++){sum += i;}}System.out.println("id: " + id + ",\t" + n + ": " + sum);Thread.yield(); // now the CPU could transfer the thread to a new Thread}}
結論,從這個測試上看兩者在多線程的實現上都可以完成,任務的分發,目前沒什麼區別
兩者輸出相似都如:id是線程的id, 後面的數字是Fibonacci數列n個項的和