有 Java 编程相关的问题?

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

java中的多线程执行时间

我有一个java线程,其中调用了方法。。我正在为每个线程存储一个映射,这样我就可以杀死它。 我的示例代码是:

 Thread thread = new Thread( new Runnable() {

        public void run() {

            executeMethod();

        }
    } );

    thread.start();
   thread.setName("some Name");
   //Create Map to save each method call as thread
    threadMap.put( "some Name", thread );

现在,我想通过终止线程来停止方法调用,所以我有如下操作:

public static void stop( String threadName ) {

    if ( StringUtils.isNotEmpty( threadName ) ) {
        Thread t = threadMap.get( threadName );

        if ( t != null && t.isAlive() ) {
            System.out.println( "Going to kill the thread:" + threadName );
            t.interrupt();
            System.out.println( "killed!!" );
        } else {
            System.out.println( "THREAD is null" );
        }
    }

}

问题是当我调用stop方法时,t.isAlive()是false。我假设方法的执行时间是线程的活动时间。。我是对的还是误解了


共 (1) 个答案

  1. # 1 楼答案

    线程在run()方法返回后也会死亡。在这种情况下,线程将不活动。将sleep语句添加到run()方法中,并在其前后添加print语句,以确保线程的当前状态

    Thread.interrupt不会终止线程,只是在线程暂停时恢复线程,通常手动终止线程不是一个好主意。阅读this question以了解为什么以及应该做什么