gpt4 book ai didi

java - 如何在Java中停止线程

转载 作者:行者123 更新时间:2023-12-03 13:17:08 24 4
gpt4 key购买 nike

我正在编写一个程序,生成一个介于1到1,000之间的随机数。然后,它使用三个线程的线程池来搜索1到1,000范围内的某些数字范围。线程检查其范围内的每个数字,并将其与随机目标数字进行比较(如果匹配),控制台上会显示消息。如果数字不匹配,这也会反射(reflect)在控制台消息中。我试图弄清楚一旦达到目标编号,如何结束程序,即使已经找到目标,也不会继续分析编号。谢谢你。

这是FindIt类:

/** fill in later */
public class FindIt extends Thread
{
private int numToFind;
private int numToStart;
private int numToEnd;

public FindIt( int nF, int nS, int nE )
{
numToFind = nF;
numToStart = nS;
numToEnd = nE;
}

public void run()
{
int counter = 0;

int numAt = numToStart;

for ( int i = 0; i < ( numToEnd - numToStart ) + 1; i++ )
{
counter++;

if ( counter == 10 )
{
counter = 0;
Thread.yield();
}

if ( numAt++ == numToFind )
{
System.out.println( "The target number, " + numToFind + ", has been found by " + Thread.currentThread().getName() + "." );
}

else
{
System.out.println( Thread.currentThread().getName() + " has analyzed the number " + ( numAt - 1 ) + " - not the target number." );
}

}
}
}

这是带有主要方法的程序:
import java.util.Random; //imports Java's Random class
import java.util.concurrent.*;

/** fill in later */
public class NumberSearch
{
public static void main( String [] args )
{
Random r = new Random(); //creates an instance of the Random class
int randomNum = r.nextInt( 1001 ); //declares the integer randomNum and initilizes it to be a random interger in the range 0 inclusive to 1001 exclusive

ExecutorService executor = Executors.newFixedThreadPool( 3 );

FindIt find1 = new FindIt( randomNum, 0, 349);
FindIt find2 = new FindIt( randomNum, 350, 699);
FindIt find3 = new FindIt( randomNum, 700, 1000);

executor.execute( find1 );
executor.execute( find2 );
executor.execute( find3 );

executor.shutdown();
}
}

最佳答案

需要两件事:

  • 通过检查Thread.currentThread().isInterrupted()并使任务在检测到中断时返回,使您的任务对中断做出响应。
  • 使用ExecutorService的shutdownNow方法来中断当前正在运行的任务。 shutdown方法使执行程序停止接收新任务,但使已经提交给执行程序的任务运行完毕。

  • 为此,不要将Thread子类化,您应该扩展Runnable或Callable以便定义提交给Executor的任务。对线程进行子类化意味着任务分配了一个OS线程,这是不必要的,因为实际的线程已经在线程池中创建了。对于此示例,由于您要在任务中计算数字,因此使用Callable可能有意义。

    java.util.concurrent中有一个用于此类事情的现有类。一旦找到答案,取消任务的示例在 API documentation for ExecutorCompletionService中给出。

    FindIt更改为检测中断:
    public class FindIt implements Runnable
    {
    private int numToFind;
    private int numToStart;
    private int numToEnd;

    public FindIt( int nF, int nS, int nE )
    {
    numToFind = nF;
    numToStart = nS;
    numToEnd = nE;
    }

    public void run()
    {
    int counter = 0;

    int numAt = numToStart;

    for ( int i = 0; i < ( numToEnd - numToStart ) + 1; i++ )
    {
    if (Thread.currentThread().isInterrupted()) {
    System.out.println(Thread.currentThread().getName()
    + " detected interruption, exiting");
    return;
    }
    counter++;

    if ( counter == 10 )
    {
    counter = 0;
    Thread.yield();
    }

    if ( numAt++ == numToFind )
    {
    System.out.println( "The target number, " + numToFind + ", has been found by " + Thread.currentThread().getName() + "." );
    }

    else
    {
    System.out.println( Thread.currentThread().getName() + " has analyzed the number " + ( numAt - 1 ) + " - not the target number." );
    }

    }
    }
    }

    关于java - 如何在Java中停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36943429/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com