三个线程分别完成1-10,11-20,21-30,相加
public class SumThread implements Runnable{
private Sum sd;
private int sum=0;
private String name;
public SumThread(String name,Sum sd){
this.name = name;
this.sd = sd;
}
public void run(){
try {
for (int i = 0; i <10; i++) {
sum += sd.add();
}
Thread.sleep(1000);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println((e.toString()));
}
System.out.println(name+"累加和为"+sum);
}
public int getSum(){
return sum;
}
}
这运行main试试,线程休眠1000ms
public static void main(String[] args) throws InterruptedException {
Sum sd =new Sum();
SumThread str1=new SumThread("1",sd);
SumThread str2=new SumThread("2",sd);
SumThread str3=new SumThread("3",sd);
Thread th1=new Thread(str1);
Thread th2=new Thread(str2);
Thread th3=new Thread(str3);
th1.start();
th2.start();
th3.start();
th1.join();System.out.println("线程1完成的sum="+str1.getSum());
th2.join();System.out.println("线程2完成的sum="+str2.getSum());
th3.join();System.out.println("线程3完成的sum="+str3.getSum());
System.out.println("总和="+(str1.getSum()+str2.getSum()+str3.getSum()));
}