有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java中断或退出线程

我有一个线程可以执行几个不同的任务。每个任务都取决于前一个任务是否成功

如果这是一种我可能会写的方法(长文):

public boolean outerMethod()
{
    boolean success= performTask();

    if(success == false)
    {
        return false;
    } 

   // more processing here if success == true
}

并从outerMethod返回给调用方,并且不会发生进一步的处理

但是

如果我在线程的run()方法中,并且执行如下所示的操作

如何在那里结束当前线程

public void run()
{
    boolean success = performTask();

    if( success == false )
    {
        /* here is where I want to exit this thread */
    }   

    // further processing if success == true
}

共 (3) 个答案

  1. # 1 楼答案

    run()方法的执行完成时,线程的执行就完成了,因此您可以正常地从该方法返回,就像您在outerMethod()中所做的那样(尽管您只是return;,因为没有返回值)

  2. # 2 楼答案

    您只需在没有值的情况下调用return即可在前面退出void方法

    public void run() {
        boolean success = performTask();
    
        if( success == false ){
            return; //ends the thread
        }   
        // further processing if success == true
    }
    
  3. # 3 楼答案

    螺纹止动块()已折旧。改用target。当没有进一步的工作时,线程将退出

    public void run()
    {
        boolean success = performTask();
    
        if(success)
        {
            // further processing if success == true
        }   
    
       //thread will exit here
    }
    

    和旁注

    使用

    if(success) instead of if(success==true) and use if(!success) instead of  if(success!=true)