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

该博客介绍编写Java程序,通过实现Runnable接口创建线程。创建两个线程对象,分别计算1到50之间奇数和偶数的和,并将结果打印到屏幕上。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值