【问题标题】:Effect of Thread.sleep on a runnable task waiting on windows to complete file creation/movingThread.sleep 对在 Windows 上等待完成文件创建/移动的可运行任务的影响
【发布时间】:2017-02-06 14:44:16
【问题描述】:

我的情况是,Windows 文件夹上的文件移动/创建正在为使用该路径上的文件继续执行的任务造成时间问题

所以我正在使用 thread.sleep(30ms) 让运行该任务的守护线程休眠,直到 Windows 可以正常工作并允许我的任务在没有任何 FileNotFoundException 的情况下正常运行。

初始化类

 Thread t = new Thread (processTask);
 t.setdaemon(true)
 t.start();

任务类

 class ProcessTask() extends Runnable 
  {
   Files.move(source, destination, copyoption);
   Thread.sleep(30ms); //to wait for windows to complete move
   new FileInputstream(sourceFile);
  }

thread.sleep(30ms) 肯定只会让我当前的守护线程睡眠 吗?有没有办法确认睡眠在哪里起作用

【问题讨论】:

  • 您的代码自相矛盾。如果你从source 移动到destination,那么之后你应该很明显不能打开源代码,但是,当然,sourceFile 是一个完全不参与操作的变量。此外,FileInputstream 使用的库代码与 NIO 不同。假设 destinationPath 代表您实际想要打开的内容,我会尝试使用 Files.newInputStream(destination)

标签: java multithreading threadpool daemon thread-sleep


【解决方案1】:

Thread.sleep() 影响当前线程。它不会让其他线程进入睡眠状态。

但是,将Thread.sleep() 用于程序逻辑绝不是一个好主意。尤其是在等待其他操作完成时。这些应该通过通知机制来处理,而不是等待随机数量并希望一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-03
    • 2018-08-22
    • 1970-01-01
    • 2014-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-22
    相关资源
    最近更新 更多