通过实现Runnable接口,编写程序来创建线程, *并创建两个线程对象,以计算奇数和偶数的总和 (奇数和偶数)1到50岁之间的分别,在屏幕上打印结果。

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

你可能感兴趣的:(java,java,thread,多线程)