Stop Executing Further Code in Java – 停止继续执行 Java 代码

最后修改: 2023年 9月 5日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

We know that it’s possible to stop execution after a certain time duration in Java. Sometimes, there may be scenarios where we want to stop the execution of further code under certain conditions. In this tutorial, we’ll explore different solutions to this problem.

我们知道,在 Java 中可以在一定时间后停止执行。有时,我们可能会希望在某些条件下停止执行更多代码。在本教程中,我们将探讨这一问题的不同解决方案。

2. Introduction to the Problem

2.问题介绍

Stopping the execution of further code can be useful in situations where we want to terminate a long-running process, interrupt a running Thread, or handle exceptional cases. This enhances control and flexibility in our program.

在我们想要终止一个长期运行的进程、中断一个正在运行的线程或处理特殊情况时,停止进一步代码的执行非常有用。这增强了我们程序的控制性和灵活性。

Stopping the execution of further code enables efficient resource utilization, allows proper error handling, and allows graceful handling of unexpected situations. This can be helpful in these areas:

停止执行更多代码可提高资源利用效率,允许适当的错误处理,并允许优雅地处理意外情况:

  • Efficient CPU Utilization
  • Memory Management
  • File and I/O Resources
  • Power Management

An example could be running a Thread in the background. We know that creating and running a Thread is costly in computational terms. When we no longer need a background Thread, we should interrupt and stop it to save computational resources:

在后台运行 Thread 就是一个例子。我们知道,创建和运行 Thread 的计算成本很高。当我们不再需要后台 Thread 时,我们应该中断并停止它,以节省计算资源:

@Override
public void run() {
    while (!isInterrupted()) {
        if (isInterrupted()) {
            break;
        }
        // complex calculation
    }
}

3. Using the return Statement

3.使用 return 语句

Mathematically, the factorial of a non-negative integer n, denoted as n!, is the product of all positive integers from 1 up to n. The factorial function can be defined recursively:

从数学上讲,非负整数 n 的阶乘(表示为 n!)是所有从 1 到 n 的正整数的乘积。阶乘函数可以递归定义:

n! = n * (n - 1)!
0! = 1

The calculateFactorial(n) method below calculates the product of all positive integers less or equal to n:

下面的 calculateFactorial(n) 方法计算所有小于或等于 n 的正整数的乘积:

int calculateFactorial(int n) {
    if (n <= 1) {
        return 1; // base case
    }
    return n * calculateFactorial(n - 1);
}

Here, we use the return statement as the base case of this recursive function. If n is 1 or less, the function returns 1. But if n is greater than or equal to 2, the function calculates the factorial and returns the value.

在这里,我们使用 return 语句作为该递归函数的基例。如果 n1 或更小,函数将返回 1。但如果 n 大于或等于 2,函数将计算阶乘并返回值。

Another example of a return statement could be downloading a file. If fileUrl and destinationPath are null or empty in the download() method, we stop executing further code:

return 语句的另一个例子是下载文件。如果 download() 方法中的 fileUrldestinationPathnull 或空,我们将停止执行进一步的代码:

void download(String fileUrl, String destinationPath) throws MalformedURLException {
    if (fileUrl == null || fileUrl.isEmpty() || destinationPath == null || destinationPath.isEmpty()) {
        return;
    }
    // execute downloading
    URL url = new URL(fileUrl);
    try (InputStream in = url.openStream(); FileOutputStream out = new FileOutputStream(destinationPath)) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

4. Using break Statements in Loops

4.在循环中使用 break 语句

To calculate the sum of an array, we can use a simple Java for loopBut when there is a negative value in the array the method stops calculating further values of the array, and the break statement terminates the loop. As a result, the control flow is redirected to the statement immediately following the end of the for loop:

要计算数组的总和,我们可以使用一个简单的 Java for 循环但是,当数组中出现负值时,方法将停止计算数组的其他值,break语句将终止循环

int calculateSum(int[] x) {
    int sum = 0;
    for (int i = 0; i < 10; i++) {
        if (x[i] < 0) {
            break;
        }
        sum += x[i];
    }
    return sum;
}

To exit a particular iteration of a loop, we can use the break statement to exit out of the scope of the loop:

要退出循环的特定迭代,我们可以使用 break 语句退出循环的范围:

@Test
void givenArrayWithNegative_whenStopExecutionInLoopCalled_thenSumIsCalculatedIgnoringNegatives() {
    StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode();
    int[] nums = { 1, 2, 3, -1, 1, 2, 3 };
    int sum = stopExecutionFurtherCode.calculateSum(nums);
    assertEquals(6, sum);
}

5. Using a break Statement in Labeled Loops

5.在标记循环中使用 break 语句

A labeled break terminates the outer loop. Once the outer loop completes its iterations, the program’s execution naturally moves to the subsequent statement.

标记为break的语句将终止外循环。一旦外循环完成迭代,程序的执行自然会转到后续语句。

Here, the processLines() method takes an array of String and prints the line. However, when the program encounters a stop in the array, it discontinues printing the line and exits the labeled loop’s scope using the break statement:

在这里,processLines() 方法接收 String 数组并打印行。但是,当程序在数组中遇到 stop 时,就会停止打印该行,并使用 break 语句退出标记循环的范围:

int processLines(String[] lines) {
    int statusCode = 0;
    parser:
    for (String line : lines) {
        System.out.println("Processing line: " + line);
        if (line.equals("stop")) {
            System.out.println("Stopping parsing...");
            statusCode = -1;
            break parser; // Stop parsing and exit the loop
        }
        System.out.println("Line processed.");
    }
    return statusCode;
}

6. Using System.exit()

6.使用 System.exit()

To stop the execution of further code, we can use a flag variable. System.exit(0) is commonly used to terminate the currently running Java program with an exit status of 0.

要停止继续执行代码,我们可以使用标志变量System.exit(0)通常用于终止当前运行的 Java 程序,其退出状态为0

Here, we use conditional statements to determine whether the program should continue running or terminate:

在这里,我们使用条件语句来决定程序是继续运行还是终止:

public class StopExecutionFurtherCode {

    boolean shouldContinue = true;

    int performTask(int a, int b) {
        if (!shouldContinue) {
            System.exit(0);
        }
        return a + b;
    }

    void stop() {
        this.shouldContinue = false;
    }
}

We terminate the program using System.exit(0) before reaching the return statement if shouldContinue is false.

如果 shouldContinuefalse,我们将在到达 return 语句之前使用 System.exit(0) 终止程序。

If the performTask() method is called with the arguments 10 and 20, and the shouldContinue state is false, the program halts its execution. Rather than giving the sum of the numbers, this method terminates the program:

如果调用参数为 1020performTask() 方法,并且 shouldContinue 状态为 false,程序将停止执行。该方法不是给出数字之和,而是终止程序:

StopExecutionFurtherCode stopExecution = new StopExecutionFurtherCode();
stopExecution.stop();
int performedTask = stopExecution.performTask(10, 20);

There are a lot of long-running tasks when doing batch processing. We can notify the operating system about the status after finishing batch processing. When we use System.exit(statusCode), the operating system can determine whether the shutdown was normal or abnormal. We can use System.exit(0) for normal shutdowns and System.exit(1) for abnormal shutdowns.

在进行批处理时,会有很多长时间运行的任务。我们可以在完成批处理后通知操作系统有关状态。当我们使用 System.exit(statusCode) 时,操作系统可以判断关机是正常还是异常。正常关闭时,我们可以使用 System.exit(0) ;异常关闭时,我们可以使用 System.exit(1)

7. Using an Exception

7.使用 异常</em

Exceptions are unexpected errors or abnormal conditions that applications face and need to be handled appropriately. It’s essential to know about errors and exceptions. In this example, we need generics to check the parameter type. If the parameter type is Number, we use an Exception to stop the execution of the method:

异常是应用程序面临的意外错误或异常情况,需要妥善处理。了解错误和异常至关重要。在本例中,我们需要使用泛型来检查参数类型。如果参数类型是 数字,我们将使用 异常来停止方法的执行:

<T> T stopExecutionUsingException(T object) {
    if (object instanceof Number) {
        throw new IllegalArgumentException("Parameter can not be number.");
    }
    T upperCase = (T) String.valueOf(object).toUpperCase(Locale.ENGLISH);
    return upperCase;
}

Here, we see that whenever we pass a Number as a parameter, it throws an Exception. On the other hand, if we pass String as the input parameter, it returns the uppercase of the given String:

在这里,我们可以看到,只要我们将 Number 作为参数传递,就会抛出 Exception 异常。另一方面,如果我们传递 String 作为输入参数,它会返回给定 String 的大写字母:

@Test
void givenName_whenStopExecutionUsingExceptionCalled_thenNameIsConvertedToUpper() {
    StopExecutionFurtherCode stopExecutionFurtherCode = new StopExecutionFurtherCode();
    String name = "John";
    String result1 = stopExecutionFurtherCode.stopExecutionUsingException(name);
    assertEquals("JOHN", result1);
    try {
        Integer number1 = 10;
        assertThrows(IllegalArgumentException.class, () -> {
            int result = stopExecutionFurtherCode.stopExecutionUsingException(number1);
        });
    } catch (Exception e) {
        Assert.fail("Unexpected exception thrown: " + e.getMessage());
    }
}

In this example, we used the basics of Java generics. Generics are useful for type safety, compile-time type checking, collection framework, etc.

在本例中,我们使用了 Java泛型的基础知识。泛型在类型安全、编译时类型检查、集合框架等方面非常有用。

8. Using the interrupt() Method in Thread

8.在 Thread 中使用 interrupt() 方法

Let’s create a class called InterruptThread to use the interrupt() method in a running thread.

让我们创建一个名为 InterruptThread 的类,以便在运行线程中使用 interrupt() 方法。

When a thread is interrupted, it sets the interrupt flag of the thread, indicating that it has been requested to stop. If the thread gets an interrupt signal, it stops the while loop scope in the program:

当线程被中断时,它会设置该线程的中断标志,表明它已被请求停止。如果线程收到中断信号,它就会停止程序中的 while 循环范围:

class InterruptThread extends Thread {
    @Override
    public void run() {
        while (!isInterrupted()) {
            break;
            // business logic
        }
    }
}

We need to start a thread using the start() method and pause the program for 2000ms. Then using the interrupt() signal stops the execution in the while loop and stops the thread:

我们需要 使用 start() 方法启动线程,并将程序暂停 2000 毫秒。然后使用 interrupt() 信号停止 while 循环中的执行并停止线程:

@Test
void givenThreadRunning_whenInterruptCalled_thenThreadExecutionIsStopped() throws InterruptedException {
    InterruptThread stopExecution = new InterruptThread();
    stopExecution.start();
    Thread.sleep(2000);
    stopExecution.interrupt();
    stopExecution.join();
    assertTrue(!stopExecution.isAlive());
}

9. Conclusion

9.结论

In this article, we’ve explored multiple programmatic ways to stop the execution of further code in Java programs. To halt a program, we can use System.exit(0) for immediate termination. Alternatively, return and break statements help to exit particular methods or loops, while exceptions allow for the interruption of code execution.

在这篇文章中,我们探讨了在 Java 程序中停止继续执行代码的多种编程方法。要停止程序,我们可以使用 System.exit(0) 来立即终止程序。另外,returnbreak 语句有助于退出特定的方法或循环,而异常则允许中断代码的执行。

As always, the complete code samples for this article can be found over on GitHub.

一如既往,本文的完整代码示例可在 GitHub 上找到