Java 多線程的兩種簡單實現方法__Java

來源:互聯網
上載者:User

簡述:

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個項的和


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.