Java Thread.sleep()是否会释放处理器?

时间:2016-06-05 16:13:34

标签: java multithreading jvm thread-safety cpu

我在服务器中有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;
}

2 个答案:

答案 0 :(得分:5)

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

然而,在重新编辑时,您的代码会在从网络读取时花费大部分时间。将睡眠添加到此代码中是完全没有意义的。别。操作系统已经知道如何安排,并且TCP已经知道如何共享带宽。

答案 1 :(得分:2)

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