Thread.sleep 有什么用
Posted 抓手
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Thread.sleep 有什么用相关的知识,希望对你有一定的参考价值。
Thread.sleep()是native方法。一个线程在运行native方法后,返回到Java线程时,必须进行一次safepoint检查。程序只有达到safepoint才会STW,从而进行GC。
Thread.sleep(0)可以让线程进入safepoint检查,从而触发GC。
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds, subject to
* the precision and accuracy of system timers and schedulers. The thread
* does not lose ownership of any monitors.
*
* @param millis
* the length of time to sleep in milliseconds
*
* @throws IllegalArgumentException
* if the value of @code millis is negative
*
* @throws InterruptedException
* if any thread has interrupted the current thread. The
* <i>interrupted status</i> of the current thread is
* cleared when this exception is thrown.
*/
public static native void sleep(long millis) throws InterruptedException;
使用案例RocketMQ :
org.apache.rocketmq.store.logfile.DefaultMappedFile#warmMappedFile
public void warmMappedFile(FlushDiskType type, int pages)
long beginTime = System.currentTimeMillis();
ByteBuffer byteBuffer = this.mappedByteBuffer.slice();
int flush = 0;
long time = System.currentTimeMillis();
for (int i = 0, j = 0; i < this.fileSize; i += MappedFile.OS_PAGE_SIZE, j++)
byteBuffer.put(i, (byte) 0);
if (type == FlushDiskType.SYNC_FLUSH)
if ((i / OS_PAGE_SIZE) - (flush / OS_PAGE_SIZE) >= pages)
flush = i;
mappedByteBuffer.force();
if (j % 1000 == 0)
log.info("j=, costTime=", j, System.currentTimeMillis() - time);
time = System.currentTimeMillis();
try
Thread.sleep(0);
catch (InterruptedException e)
log.error("Interrupted", e);
if (type == FlushDiskType.SYNC_FLUSH)
log.info("mapped file warm-up done, force to disk, mappedFile=, costTime=",
this.getFileName(), System.currentTimeMillis() - beginTime);
mappedByteBuffer.force();
log.info("mapped file warm-up done. mappedFile=, costTime=", this.getFileName(),
System.currentTimeMillis() - beginTime);
this.mlock();
详细解释:
以上是关于Thread.sleep 有什么用的主要内容,如果未能解决你的问题,请参考以下文章