Write a program to create a thread by implements Runnable Interface, and create two thread objects, to calculate the sum of the odd and even between 1 and 50, respectively, and print the results on the screen.
package week15;
/*
Write a program to create a thread by implements Runnable Interface,
and create two thread objects, to calculate the sum of the odd and even
between 1 and 50, respectively, and print the results on the screen.
*/
class mythread2 implements Runnable{
String m;int sum=0;
public mythread2(String m) {
this.m=m;
}
public void run() {
for (int i = 1; i <=50; i+=2) {
sum+=i;
}
System.out.println("1~50的"+m+"和为:"+sum);
}
}
public class t2 {
public static void main(String[] args) {
mythread2 h1=new mythread2("奇数");
mythread2 h2=new mythread2("偶数");
h1.run();
h2.run();
}
}
The result:
1~50的奇数和为:625
1~50的偶数和为:625