【问题标题】:Does Java Thread.sleep() release the processor?Java Thread.sleep() 是否释放处理器?
【发布时间】:2016-06-05 16:13:33
【问题描述】:

我在服务器中有 CPUx2,并且我有一个包含许多线程的程序,如果所有线程都需要很长时间来做某事,是否可以使用 Thread.Sleep(10) 来让 CPU 释放作业到另一个线程?我可以只使用thread.sleep,它会让CPU自动切换另一个线程以提高或增强性能吗?

2016/06/06 更新: 每个线程都专注于使用 Executors 从 Internet 获取 HTTP 内容,虽然我想给它延迟更多的时间来做,但我不确定当我在里面的代码中添加 TimeUnit.MILLISECONDS.sleep(10) 时是否使用MILLISECONDS 或 NANOSECOND 以及让 CPU 自动切换另一个线程的时间槽,以便整体性能公平:

@Override
public void run() {
    //this.RunActual = System.currentTimeMillis();

    if ("Started".equals(this.JobStatus)) {
        String startDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
        System.out.println(this.HttpRequestAddress + " has started at " + startDate);
        try {
            this.url = new URL("http://" + this.HttpRequestAddress + ":" + this.HttpRequestPort);
            this.conn = (HttpURLConnection) this.url.openConnection();
            this.conn.setRequestMethod(this.HttpRequestMethod);
            this.conn.setReadTimeout(this.HttpRequestReadTimeout);
            this.conn.setConnectTimeout(this.HttpRequestConnectionTimeout);
            this.conn.setInstanceFollowRedirects(false);
            for (HttpHeader hh : this.HttpRequestHeader) {
                this.conn.setRequestProperty(hh.Name, hh.Value);
            }
            this.conn.connect();
            this.responseCode = 0;
            this.responseCode = this.conn.getResponseCode();
            System.out.println(this.HttpRequestAddress + " has response header " + this.conn.getHeaderFields().toString());
            if (this.responseCode == HttpURLConnection.HTTP_OK) {
                if (this.HttpResponseKeyword != null) {
                    boolean hasKeyword = false;
                    this.br = new BufferedReader(new InputStreamReader(this.conn.getInputStream(), this.httpResponseEncoding));
                    while ((this.charRead = this.br.read(this.buffer, 0, this.BUFFER_SIZE)) > 0) {
                        this.sb.append(this.buffer, 0, this.charRead);
                        //System.out.println(this.sb.toString());
                        if (this.HttpResponseContain && this.sb.indexOf(this.HttpResponseKeyword) > 0) {
                            hasKeyword = true;
                            break;
                        }
                        this.sb.setLength(0);
                        TimeUnit.MILLISECONDS.sleep(10);
                    }
                    if (this.HttpResponseContain && hasKeyword) {
                        System.out.println(this.HttpRequestAddress + " should include keyword, now it is included.");
                    } else if (this.HttpResponseContain && !hasKeyword) {
                        System.out.println(this.HttpRequestAddress + " should include keyword, but it is not included.");
                    } else if (!this.HttpResponseContain && !hasKeyword) {
                        System.out.println(this.HttpRequestAddress + " should not include keyword, now it is not included.");
                    } else if (!this.HttpResponseContain && hasKeyword) {
                        System.out.println(this.HttpRequestAddress + " should not include keyword, but it is included.");
                    }
                }
            }
        } catch (Exception ex) {
            String errorDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
            System.err.println(this.HttpRequestAddress + " has error at " + errorDate + " with " + ex.toString());
        }
        String endDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS").format(Calendar.getInstance().getTime());
        System.out.println(this.HttpRequestAddress + " has end at " + endDate);
    }

    /*
    if (this.RunNext != 0) {
        long c = this.RunActual - this.RunNext;
        if (c > 0) {
            System.out.println(this.HttpRequestAddress + " has slowed " + c + " milliseconda.");
        }
    }*/

    //this.RunNext = System.currentTimeMillis() + this.JobInterval;
}

【问题讨论】:

  • 这个问题太笼统了。这取决于线程在做什么。有些人可能会质疑您为什么要使用很多线程。请显示您的问题的代码示例,表达您的问题
  • 您要解决的问题是什么?如果线程 100% 使用您的 CPU,那么它们会以尽可能快的速度运行,添加 sleep() 不会提高整体性能。这些工作仍然必须完成。您是否试图“限制”它们,减慢它们的速度,以便它们使用更少的 CPU?为什么?如果您只是希望其他程序正常运行,请降低线程的线程优先级。这样他们将使用所有可用的 CPU,但仍然允许其他程序以最小的延迟运行。
  • 几乎没有任何好的理由打电话给Thread.sleep()。如果您在实时应用程序中使用它来让事情在正确的时刻发生,那么您最好使用标准 JRE 的 ScheduledThreadPoolExecutor 类或某些 GUI 框架的 Timer 类。如果您使用它来平衡不同线程完成的工作量,那么可能还有其他更好的方法。如果您使用它来确保事情以正确的顺序发生,那么您可能犯了一个严重的错误。

标签: java multithreading jvm thread-safety cpu


【解决方案1】:

Thread.sleep() 将处理器释放到另一个可运行的线程或进程,并将当前线程标记为不可运行,直到休眠时间到期。

但是,在重新您的编辑时,您的代码大部分时间都会在从网络读取时被阻塞。在这段代码中添加睡眠是完全没有意义的。不。操作系统已经知道如何调度,TCP 也已经知道如何共享带宽。

【讨论】:

    【解决方案2】:

    正如您推测的那样,调用Thread.sleep() 会释放大多数主要操作系统中的处理器。但是,在大多数操作系统上,您不需要调用Thread.sleep() 来释放处理器,因为无论如何操作系统都会每隔一段时间切换到其他线程。与不断检查完成条件的循环相比,使用Thread.sleep() 可能会提高效率,但更好的解决方案通常是使用等待和通知,以便线程可以在需要时唤醒,而不必每隔一段时间进行检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 1970-01-01
      • 2014-03-21
      • 2021-01-10
      相关资源
      最近更新 更多