重新实例化线程
我有以下代码,有人可以在下面澄清我的疑问吗?
public static void Main() {
Thread thread = new Thread(Display);
thread.Start();
Thread.Sleep(5000);
// Throws exception, thread is terminated, cannot be restarted.
thread.Start()
}
public static void Display() {
}
似乎为了重新启动线程,我必须再次重新实例化线程。这是否意味着我正在创建一个新线程?如果我继续创建 100 次重新启动,是否会创建 100 个线程并导致性能问题?
I have the following code, could anyone please clarify my doubt below.
public static void Main() {
Thread thread = new Thread(Display);
thread.Start();
Thread.Sleep(5000);
// Throws exception, thread is terminated, cannot be restarted.
thread.Start()
}
public static void Display() {
}
It seems like in order to restart the thread I have to re-instantiate the thread again. Does this means I am creating a new thread? If I keep on creating 100 re-instiation will it create 100 threads and cause performance issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
是的,您要么必须创建一个新线程,要么每次都将任务交给线程池,以避免创建真正的新线程。您无法重新启动线程。
但是,我建议,如果您的任务连续执行 100 次失败,那么您遇到的问题比启动新任务的性能开销更大。
Yes, you either have to create a new thread or give the task to the thread pool each time to avoid a genuinely new thread being created. You can't restart a thread.
However, I'd suggest that if your task has failed to execute 100 times in a row, you have bigger problems than the performance overhead of starting new tasks.
sleep
后不需要启动线程,线程会自动唤醒。这是同一个线程。You do not need to start the thread after
sleep
, the thread wake up automatically. It's the same thread.首先,如果线程已经启动,则无法启动该线程。在您的示例中,线程已完成工作,这就是它处于终止状态的原因。
您可以使用以下方式检查状态:
线程.线程状态
first of all, you can't start the thread if it has already started. In your example, thread has finished it is work, that's why it is in terminated state.
you can check status using:
Thread.ThreadState
您是否尝试在 5 秒完成之前唤醒线程?在这种情况下,您可以尝试使用监视器(等待、脉冲等)
Are you trying to wake the thread up before the 5 seconds in complete? In which case you could try using Monitor (Wait, Pulse etc)