请使用“匿名Runnable”子类的方式实现线程,线程中计算1--500所有数字的累加和,并打印计算结果。
时间: 2023-06-01 17:07:12 浏览: 73
好的,这是一道关于编程的问题,我可以回答。
以下是将一个匿名Runnable子类用于计算数字累加和的代码示例:
```java
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
int sum = 0;
for (int i = 1; i <= 500; i++) {
sum += i;
}
System.out.println("计算结果为:" + sum);
}
});
thread.start();
```
这里创建了一个Thread对象,并且将一个匿名Runnable子类传递给了Thread构造函数。该子类实现了run()方法,用于计算数字累加和并打印结果。最后,调用了start()方法启动这个线程并执行该子类中的run()方法。
相关问题
JAVA计算1-100的和并输出, 用两种线程方式实现。
好的,这个问题可以直接回答。以下是两种线程方式的实现:
1. 继承Thread类的方式:
```
public class SumThread extends Thread {
int sum = 0;
int start, end;
public SumThread(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
SumThread t1 = new SumThread(1, 50);
SumThread t2 = new SumThread(51, 100);
t1.start();
t2.start();
t1.join();
t2.join();
int totalSum = t1.getSum() + t2.getSum();
System.out.println("1-100的和为:" + totalSum);
}
}
```
2. 实现Runnable接口的方式:
```
public class SumRunnable implements Runnable {
int sum = 0;
int start, end;
public SumRunnable(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
for (int i = start; i <= end; i++) {
sum += i;
}
}
public int getSum() {
return sum;
}
}
public class Main {
public static void main(String[] args) throws InterruptedException {
SumRunnable r1 = new SumRunnable(1, 50);
SumRunnable r2 = new SumRunnable(51, 100);
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.join();
t2.join();
int totalSum = r1.getSum() + r2.getSum();
System.out.println("1-100的和为:" + totalSum);
}
}
```
希望能够帮助您!
定义一个类实现Runnable接口实现线程应用,该线程实现1-10的输出
好的,下面是实现代码:
```java
public class CountThread implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
CountThread countThread = new CountThread();
Thread thread = new Thread(countThread);
thread.start();
}
}
```
这里我们定义了一个名为`CountThread`的类,实现了`Runnable`接口,重写了`run()`方法,在`run()`方法中循环输出1-10的数字。在`main()`方法中,我们创建了一个新的线程,将`CountThread`对象作为参数传入,然后启动该线程。当运行该程序时,将输出1-10的数字。