黑马程序员技术交流社区
标题:
这串代码的红色这一行我不是很懂,那位大神赐教!!
[打印本页]
作者:
杜弦东.
时间:
2015-7-13 00:14
标题:
这串代码的红色这一行我不是很懂,那位大神赐教!!
//编写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);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2