當前位置:編程學習大全網 - 編程軟體 - 在安卓編程裏面,用線程計算1+到100

在安卓編程裏面,用線程計算1+到100

package cn.test;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class TestUtil {

public static void main(String[] args) {

K k = new K();

ExecutorService pool = Executors.newCachedThreadPool();

for(int i=1;i<101;i++){

pool.execute(new AddThread(k,i));

}

pool.shutdown();

// while(!pool.isTerminated()){

// try {

// Thread.sleep(1000);

// } catch (InterruptedException e) {

// e.printStackTrace();

// }

// }

System.out.println("結果為:"+k.getTotal());

}

}

class AddThread implements Runnable{

public AddThread(K k, int add) {

this.k = k;

this.add = add;

}

private K k;

private int add;

@Override

public void run() {

k.add(add);

}

}

class K{

private int total=0;

public int getTotal() {

return total;

}

public void setTotal(int total) {

this.total = total;

}

public synchronized void add(int k){

this.total=total+k;

}

}

  • 上一篇:樂高積木賽車怎麽拼
  • 下一篇:eprime可以安裝到D盤嗎
  • copyright 2024編程學習大全網