//编写10个线程,第一个线程从1加到10...最后把10线程结果相加
//继承Thread类
public class Accumulator extends Thread{
private int startNum;
public static int sum;
//带参构造
public Accumulator(int startNum){
this.startNum=startNum;
}
//同步
public static synchronized void add(int num){
sum+=num;
}
//调用run()方法
public void run(){
int sum=0;
for(int x=0;x<10;x++){
sum+=startNum+x;
}
add(sum);
}
//主函数抛出异常
public static void main(String[] args) throws Exception{
//创建10个线程
Thread[] threadList=new Thread[10];
for(int x=0;x<10;x++){
threadList[x]=new Accumulator(10*x+1);
//启动线程
threadList[x].start();
}
for(int x=0;x<10;x++){
threadList[x].join();
}
System.out.println("sum:"+sum);
}
} |