简体   繁体   中英

Does Java Thread.sleep() release the processor?

I have CPUx2 in a server and I have a program that included many threads, if all threads take a long time to do something, is it possible to use Thread.Sleep(10) in order to let CPU release job into another threads? Could I just use thread.sleep and will it let CPU to auto switch another threads in order to improve or enhance the performance?

UPDATED at 2016/06/06: Every thread is focusing on obtain HTTP content from the Internet with Executors, while I want to give it delay more time to do, but I am not so sure when I added TimeUnit.MILLISECONDS.sleep(10) in the code inside whether use either MILLISECONDS or NANOSECOND and with how many time slot that let CPU to auto switch another threads, so that the overall performance can be fair:

@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;
}

Thread.sleep() releases the processor to another runnable thread or process and marks the current thread as not runnable until the sleep time expires.

HOWEVER, and in re your edit, your code will spend most of its time blocked while reading from the network. Adding sleeps into this code is completely pointless. Don't. The operating system already knows how to schedule, and TCP already knows how to share bandwidth.

As you surmise, calling Thread.sleep() releases the processor in most major operating systems. However, you do not need to call Thread.sleep() to release the processor on most operating systems, as the operating system will switch to other threads at intervals anyway. Using Thread.sleep() may improve efficiency relative to a loop that constantly checks for a completion condition, but a better solution is often to use waits and notifies so the thread can wake up when needed rather than having to check at intervals.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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