启动10个线程,第一个线程从1加到10,第二个线程从11加到20…第十个线程从91加到100,最后再把10个线程结果相加。线程类的已经完成,请完成Main类,实现输出。
裁判测试程序样例:
class Thread_test extends Thread
{
int number;
public static int sum;
public Thread_test(int n) //构造函数
{
number=n;
}
public static synchronized void add(int num){ //同步方法
sum += num;
}
public void run()
{
int count=0;
for(int i=0;i<10;i++)
{
count+=number+i;
}
System.out.println("The "+((int)number/10+1)+" time: "+count);
add(count);
}
}
/* 请在这里填写答案 */
输入样例:
无
输出样例:
The 1 time: 55
The 2 time: 155
The 3 time: 255
The 4 time: 355
The 5 time: 455
The 6 time: 555
The 7 time: 655
The 8 time: 755
The 9 time: 855
The 10 time: 955
Total is 5050
结尾无空行
这题利用主线程和子线程的思路实现输出控制,将整个逻辑放入主线程中,然后通过join()方法堵塞,确认子线程结束后再开启下一个新的子线程
虽然老师说也可以通过sleep来适应不同机器性能达到输出效果,但我没试,太不严谨了。。
答案如下
class mainThread extends Thread{
int number;
public void run(){
for(int i=1;i<100;i+=10){
Thread_test t = new Thread_test(i);
t.start();
try{
t.join();
}catch(InterruptedException e){
}
}
System.out.println("Total is " + Thread_test.sum);
}
}
public class Main{
public static void main(String args[]){
new mainThread().start();
}
}