用java创建一个线程,计算两个整数x和y(x<y)之间的所有整数之和并输出。 提示:可能用到线程的休眠、插队和停止。
时间: 2024-02-26 12:57:00 浏览: 23
好的,我来回答你的问题。
首先,我们需要创建一个线程类,让它实现 Runnable 接口。
```java
public class MyThread implements Runnable {
private int x;
private int y;
private int sum;
public MyThread(int x, int y) {
this.x = x;
this.y = y;
this.sum = 0;
}
public void run() {
for (int i = x; i <= y; i++) {
sum += i;
try {
Thread.sleep(10); // 休眠 10 毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Thread.currentThread().isInterrupted()) { // 判断线程是否被中断
System.out.println("线程被中断");
return;
}
}
System.out.println("计算结果为:" + sum);
}
}
```
在 run() 方法中,我们用一个 for 循环计算 x 和 y 之间的所有整数之和,并且在每次循环后休眠 10 毫秒。这里的休眠是为了让线程的执行速度变慢一些,以便我们后面测试插队的效果。
当线程被中断时,我们会输出一条信息,并且立即返回。
接下来,我们在主线程中创建一个 MyThread 对象,并且启动它。
```java
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread(1, 100);
Thread t = new Thread(thread);
t.start();
}
}
```
这样,我们就创建了一个线程,计算了 1 到 100 之间的所有整数之和,并且在计算完成后输出了结果。
接下来,我们来测试一下线程的插队和停止功能。
首先,我们来测试插队。我们可以在 MyThread 类中添加一个方法,让它在计算到一半时插队到主线程中执行。
```java
public void insert() {
Thread.currentThread().interrupt();
System.out.println("线程插队");
}
```
在 insert() 方法中,我们调用了 Thread.currentThread().interrupt() 方法,让线程被中断。这样,在 MyThread 类中的 for 循环里面就会抛出 InterruptedException 异常,然后线程就会跳转到 catch 块中执行。
在 catch 块中,我们输出了一条信息,并且立即返回,这样线程就被中断了。
接下来,我们在主线程中启动线程,并且在一半的时候插队。
```java
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread(1, 100);
Thread t = new Thread(thread);
t.start();
try {
Thread.sleep(50); // 等待 50 毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.insert();
}
}
```
在主线程中,我们先休眠了 50 毫秒,然后调用了 thread.insert() 方法,让线程插队。
这样,我们就测试了线程的插队功能。
接下来,我们来测试停止功能。我们可以在 MyThread 类中添加一个方法,让它在计算到一半时停止线程。
```java
public void stop() {
Thread.currentThread().interrupt();
}
```
在 stop() 方法中,我们同样调用了 Thread.currentThread().interrupt() 方法,让线程被中断。
然后,在 MyThread 类中的 for 循环里面,我们加入了一个判断语句,判断线程是否被中断。如果线程被中断了,我们就输出一条信息并且立即返回。
```java
for (int i = x; i <= y; i++) {
sum += i;
try {
Thread.sleep(10); // 休眠 10 毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
if (Thread.currentThread().isInterrupted()) { // 判断线程是否被中断
System.out.println("线程被中断");
return;
}
}
```
接下来,我们在主线程中启动线程,并且在一半的时候停止线程。
```java
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread(1, 100);
Thread t = new Thread(thread);
t.start();
try {
Thread.sleep(50); // 等待 50 毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
thread.stop();
}
}
```
在主线程中,我们先休眠了 50 毫秒,然后调用了 thread.stop() 方法,让线程停止。
这样,我们就测试了线程的停止功能。
希望这个例子能够对你有所帮助。