简体   繁体   English

我需要停止线程吗?

[英]Do I need to stop a Thread?

I'm trying to implement a separate Thread in my project. 我正在尝试在我的项目中实现一个单独的Thread Every hour a scheduler starts a thread to get files from a server and store them in my database. 每隔一小时,调度程序就会启动一个线程来从服务器获取文件并将它们存储在我的数据库中。

My code works as it should. 我的代码可以正常工作。 Since the scheduler starts a new Thread every hour, I don't know if I need to stop the Thread manually or not? 由于调度程序每小时启动一个新Thread ,我不知道是否需要手动停止Thread

 try {
        Runnable task = new MyClass();
        Thread thread = new Thread(task);
        thread.start();

 } catch (Exception ex) {
        System.err.println("Exception-Thread: " + ex.getMessage());
 }

My Class (runnable) 我的班级(可运行)

  public class MyClass implements Runnable {
        @Override
        public void run() {

            try {
                //Do stuff...
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }

如果在Runnable没有永久循环或类似的东西,那么你不需要。

As long as the thread has not chance of doing infinite loop Such as using while loop. 只要线程没有机会做无限循环就像使用while循环一样。 Thread will stop once all the tasks in Runnable are done. 一旦Runnable中的所有任务完成,线程将停止。

No, you don't need to stop the Thread manually. 不,您不需要手动停止线程。 More than that the stop() method of thread is @deprecated and not safe: 不仅如此,线程的stop()方法是@deprecated而且不安全:

This method is inherently unsafe. 这种方法本质上是不安全的。 Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked 使用Thread.stop停止线程会导致它解锁已锁定的所有监视器

Thread will finish its job when it will escape run block. Thread逃脱run块时, Thread将完成其工作。 More than that you need do to some effort to keep it running. 不仅如此,你需要做一些努力来保持它的运行。

You need to start looking into Executors framework and not operate Threads directly. 您需要开始查看Executors框架而不是直接操作Threads

Thread life cycle has following states 线程生命周期具有以下状态

New, Runnable, waiting, Timed waiting, Terminated, 新的,可运行的,等待的,定时的等待,终止,

the first thing you should not stop your thread directly as it can cause shared variable in an inconsistent state, and if you want to then you have to make a proper flow to terminate the thread. 首先你不应该直接停止你的线程,因为它可能导致共享变量处于不一致状态,如果你想,那么你必须做一个正确的流程来终止线程。

To take your thread in a terminate state you have to see if it is not in waiting, timed waiting or worse case in the active state depends how you have handled it. 要使您的线程处于终止状态,您必须查看它是否处于等待状态,定时等待或处于活动状态的更糟糕情况取决于您如何处理它。

If you are not doing any of this then need not to otherwise please make a proper method to terminate the thread. 如果你没有做任何这个,那么不用另外请做一个正确的方法来终止线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM