當前位置:編程學習大全網 - 網站源碼 - java用多線程實現累加求和

java用多線程實現累加求和

在樓上基礎上大概改壹下,增加同步處理。

public class Test extends Thread {

static int n = 0;

private int startNum = 0 ;

public Test (int sn)

{

this.startNum = sn ;

}

public static synchronized void addSum (int num)

{

n += num ;

}

public static void main(String[] args) {

Thread [] thList = new Thread [10] ;

for (int i = 0; i < 10; i ++) {

thList [i] = new Test(i * 10 + 1) ;

thList [i].start();

}

for (int i = 0 ; i < 10 ; i ++)

{

thList [i].join () ;

}

System.out.println ("Sum is : " + n) ;

}

public void run() {

int sum = 0 ;

for (int i = 0; i < 10; ++i) {

sum += sn + i ;

}

addSum (sum) ;

}

}

  • 上一篇:包圖的介紹
  • 下一篇:已知X的補碼是11101011,Y的補碼是01001010,X-Y的補碼是多少?
  • copyright 2024編程學習大全網