等待()和睡眠()的区别

What is the difference between a wait() and sleep() in Threads?

Is my understanding that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not consume any CPU cycles correct?

Why do we have both wait() and sleep(): how does their implementation vary at a lower level?

转载于:https://stackoverflow.com/questions/1036754/difference-between-wait-and-sleep

0
weixin_41568134
MAO-EYE superb question i also thought like this thank you for asked here
大约一年之前 回复
csdnceshi71
Memor.の "Thread.sleep is bad practice" if it is used instead of wait. see stackoverflow.com/questions/17826651/… But good comment through.
接近 3 年之前 回复
csdnceshi72
谁还没个明天 its EXCATLY the opposite - sleep "uses" all of its available CPU-cycles but since the thread will be in "WAITING"-state these can be yielded if necessary - in fact most operating systems automatically yield the cycles IF it is possible, hence your thread will not create any actual CPU-load ... it will do so on older operating systems, though. Object.wait(), on the other hand NEVER uses any cycles (while being unnotified) because thats realized via software-interrupts in many cases - private, transient & transparent locks, implemented by the JVM. Thread.sleep is bad practise.
4 年多之前 回复
csdnceshi77
狐狸.fox Here's a good article describing it: qat.com/using-waitnotify-instead-thread-sleep-java
接近 6 年之前 回复
csdnceshi67
bug^君 Suppose a thread A is in a synchronized block , and while it is in the cpu from this thread is taken and given to another thread B. now in which state Thread A will go , will the other threads waiting on this synchronized block come inside now ?
大约 6 年之前 回复
csdnceshi55
~Onlooker Very nice questions but they are 2 in one. Why do we have both is not the same as how they can (and not are!) implemented at a lower level. I've answered to that too.
7 年多之前 回复
csdnceshi69
YaoRaoLov very good question. semantics of both are easy to confuse.
大约 10 年之前 回复

29个回答

A wait can be "woken up" by another thread calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:

Object mon = ...;
synchronized (mon) {
    mon.wait();
} 

At this point the currently executing thread waits and releases the monitor. Another thread may do

synchronized (mon) { mon.notify(); }

(on the same mon object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.

You can also call notifyAll if more than one thread is waiting on the monitor – this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the wait is in a synchronized block) and carry on – the others will then be blocked until they can acquire the monitor's lock.

Another point is that you call wait on Object itself (i.e. you wait on an object's monitor) whereas you call sleep on Thread.

Yet another point is that you can get spurious wakeups from wait (i.e. the thread which is waiting resumes for no apparent reason). You should always wait whilst spinning on some condition as follows:

synchronized {
    while (!condition) { mon.wait(); }
}
20
csdnceshi79
python小菜 the word monitor seems to originate with Per Brinch Hansen and CAR Hoare, see stackoverflow.com/a/52005220/217324 for how usage in java seems different from the original meaning.
10 个月之前 回复
csdnceshi64
游.程 You don't need to synchronize when starting the thread, but you do need to synchronize on the call to notify. Did you try omitting the synchronization block to see what happens? An IllegalMonitorStateException will be thrown
接近 2 年之前 回复
csdnceshi68
local-host When I start the thread that will inherit the lock, should I do it inside of the synchronized block? Also, when I call lock.notify(), should that also be in a synchronized block?
接近 2 年之前 回复
csdnceshi54
hurriedly% anyone why it's everywhere called "monitor object", not monitored?
大约 2 年之前 回复
csdnceshi58
Didn"t forge Thread.sleep() is also subject to "spurious" wakeups from interrupts. In my experience, though, both for wait() and sleep(), there are no truly spurious wakeups; there are only unexpected wakeups from notify() or interrupt() calls that you didn't account for when writing the code.
大约 2 年之前 回复
weixin_41568184
叼花硬汉 Can someone tell me why this question (Difference between wait and sleep) is so hot for interviews, it's like comparing apples and oranges. As far as I understand sleep is for halting execution and wait is for thread intercommunication (waiting for some condition).
2 年多之前 回复
weixin_41568134
MAO-EYE which one use CPU cycle?
大约 3 年之前 回复
csdnceshi53
Lotus@ wait() is similiar to pthread_cond_wait() in C. So thread wait until another thread notify it and it doesn't hold object fields.
3 年多之前 回复
csdnceshi65
larry*wei this while(runner.isAlive()){this.wait();} froze here, as the Runnable.run() does the notify() and when it does that, it is still alive; I wonder if there is a way to know who notified, so if null or not the expected one, that loop on wait() would be kept, any idea?
4 年多之前 回复
csdnceshi56
lrony* Suppose a thread A is in a synchronized block , and while it is in the cpu from this thread is taken and given to another thread B. now in which state Thread A will go , will the other threads waiting on this synchronized block come inside now ?
大约 6 年之前 回复
csdnceshi75
衫裤跑路 Yes, "Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not". It will throw java.lang.IllegalMonitorStateException if do not use wait/nitify in a synchronized block.
接近 7 年之前 回复
csdnceshi59
ℙℕℤℝ wait() not only suspends the process, but if this process has any shared resources/locks, it has to give those up, until it can resume with execution.
大约 7 年之前 回复
csdnceshi69
YaoRaoLov I read through all of the answers however I still feel a bit of missing information. Many people wrote down the definitions from the Javadoc and also the meaning of the two english words but I do not see Why I should ever use sleep instead of wait? What is the benchmarking and speed difference between the two? If I can do everything that I can do with sleep why should I ever choose sleep?
大约 7 年之前 回复
csdnceshi62
"幸运的战士" Interruption is intended as a mechanism to gently encourage a thread to stop running entirely and cancel remaining operations. wait/notify are typically used to wait for some other thread to accomplish a task, or to wait until a certain condition is satisfied.
大约 7 年之前 回复
csdnceshi60
℡Wang Yan ok so we got a wait that can be notified. But we also got a sleep that can be interrupted. So comparing wait-notify vs sleep-interrupt, what's the difference?
大约 7 年之前 回复
csdnceshi60
℡Wang Yan Is Thread.sleep simply a "higher-level layer" built atop of object.wait() ? Or is it true that they are two separate things?
7 年多之前 回复
csdnceshi57
perhaps? - I could be wrong :-(
大约 10 年之前 回复
csdnceshi80
胖鸭 - why in the world do you say wait() wastes CPU cycles?
大约 10 年之前 回复
csdnceshi74
7*4 When you are interrupting, you must know which thread you want to interrupt. When you're calling notify, you just need object, and you don't care if there is any other thread which 'waits' on this object. wait/notify is used for communication, while sleep is used for, ehm, sleeping.
大约 10 年之前 回复
csdnceshi57
perhaps? but you can interrupt a sleeping Thread. In that case wait() is redundant infact it wastes CPU cycles too :-(
大约 10 年之前 回复
csdnceshi74
7*4 No, it cannot. It can only be interrupted.
大约 10 年之前 回复
csdnceshi57
perhaps? A sleeping Thread can also be woken up by notify(). ?
大约 10 年之前 回复

I found this post helpful. It puts the difference between Thread.sleep(), Thread.yield(), and Object.wait() in human terms. To quote:

It all eventually makes its way down to the OS’s scheduler, which hands out timeslices to processes and threads.

sleep(n) says “I’m done with my timeslice, and please don’t give me another one for at least n milliseconds.” The OS doesn’t even try to schedule the sleeping thread until requested time has passed.

yield() says “I’m done with my timeslice, but I still have work to do.” The OS is free to immediately give the thread another timeslice, or to give some other thread or process the CPU the yielding thread just gave up.

wait() says “I’m done with my timeslice. Don’t give me another timeslice until someone calls notify().” As with sleep(), the OS won’t even try to schedule your task unless someone calls notify() (or one of a few other wakeup scenarios occurs).

Threads also lose the remainder of their timeslice when they perform blocking IO and under a few other circumstances. If a thread works through the entire timeslice, the OS forcibly takes control roughly as if yield() had been called, so that other processes can run.

You rarely need yield(), but if you have a compute-heavy app with logical task boundaries, inserting a yield() might improve system responsiveness (at the expense of time — context switches, even just to the OS and back, aren’t free). Measure and test against goals you care about, as always.

28
csdnceshi80
胖鸭 How does the notify work at the OS scheduler level? Does notify call some sort of event handler with a particular thread id, allowing the scheduler to put the relevant thread back on the running queue? Also I have another question, where does the concept of spinlock fit in? Would it only be relevant for sleep or does wait itself use spinlock at the very low level?
大约 4 年之前 回复
csdnceshi53
Lotus@ there is no mentioning of monitors in the answer, and that is because sleep does not have any special behaviour regarding monitor than any other Java method call, that is, it does not interact or modify them in any way. If you would say something about monitors you should specify that wait will, in addition to the things said above, relinquish temporarily the lock on the object it is called on.
大约 4 年之前 回复
weixin_41568131
10.24 the explanation of sleep(n) is implicitly saying that the currently running thread relinquishes the lock's monitor voluntarily, which is not true. Quote from Thread's javadoc:"The thread does not lose ownership of any monitors."
4 年多之前 回复
weixin_41568134
MAO-EYE Yield is basically platform-dependent... javamex.com/tutorials/threads/yield.shtml
大约 5 年之前 回复

One key difference not yet mentioned is that while sleeping a Thread does not release the locks it holds, while waiting releases the lock on the object that wait() is called on.

synchronized(LOCK) {
    Thread.sleep(1000); // LOCK is held
}


synchronized(LOCK) {
    LOCK.wait(); // LOCK is not held
}
27
csdnceshi77
狐狸.fox wait() is associated with the condition of the inner most lock it's called from, in your code example, wait() can only release LOCK and not OUTER_LOCK. That's how Java monitor is designed anyway. A fair comparison would be synchronized(OUTER_LOCK){ synchronized(LOCK) { Thread.sleep(1000); } } and synchronized(OUTER_LOCK){ synchronized(LOCK) { LOCK.wait(); } }. In this case sleep() will hold both locks while wait() will release LOCK but still hold OUTER_LOCK
接近 2 年之前 回复
weixin_41568184
叼花硬汉 ..........Thus talking about explicit use of java locks is pretty off-topic already, as the question is asking about OS/JVM implementation.
大约 5 年之前 回复
weixin_41568184
叼花硬汉 Your answer misleadingly claims that sleep holds java locks, but it doesn't. To have a fair comparison, we would compare synchronized(OUTER_LOCK){ Thread.sleep(1000); } with synchronized(OUTER_LOCK){ synchronized(LOCK){LOCK.wait();} } and we can see that both instructions don't release the OUTER_LOCK. If there's any difference, we can say that sleep doesn't explicitly use java locks, but the question is asking about quote "how does their implementation vary at a lower level?" unquote.
大约 5 年之前 回复
csdnceshi72
谁还没个明天 - the fact that it does not have to be used with synchronized does not mean it can't be used. Actually, I've seen Thread.sleep calls with locks held, which in turn lead to poor application performance.
大约 5 年之前 回复
weixin_41568184
叼花硬汉 sleep doesn't have to be used with synchronized(LOCK). The code comparison you did above is a misleading one.
大约 5 年之前 回复
csdnceshi72
谁还没个明天 - what exactly is misleading? Feel free to suggest and edit.
大约 5 年之前 回复
weixin_41568184
叼花硬汉 This answer is extremely misleading... how did it get 99 upvotes?
大约 5 年之前 回复
csdnceshi72
谁还没个明天 - I'd say that you should not sleep with locks, there are few uses cases for that. Just wanted to point out the differences.
大约 10 年之前 回复
csdnceshi62
"幸运的战士" You don't actually need to call sleep from within a lock - locks and wait/notify go hand in hand but locks and sleep are unrelated.
大约 10 年之前 回复
csdnceshi51
旧行李 Waiting only releases the lock for the object you call wait() on. It doesn't release any other locks.
大约 10 年之前 回复

There are a lot of answers here but I couldn't find the semantic distinction mentioned on any.

It's not about the thread itself; both methods are required as they support very different use-cases.

sleep() sends the Thread to sleep as it was before, it just packs the context and stops executing for a predefined time. So in order to wake it up before the due time, you need to know the Thread reference. This is not a common situation in a multi-threaded environment. It's mostly used for time-synchronization (e.g. wake in exactly 3.5 seconds) and/or hard-coded fairness (just sleep for a while and let others threads work).

wait(), on the contrary, is a thread (or message) synchronization mechanism that allows you to notify a Thread of which you have no stored reference (nor care). You can think of it as a publish-subscribe pattern (wait == subscribe and notify() == publish). Basically using notify() you are sending a message (that might even not be received at all and normally you don't care).

To sum up, you normally use sleep() for time-syncronization and wait() for multi-thread-synchronization.

They could be implemented in the same manner in the underlying OS, or not at all (as previous versions of Java had no real multithreading; probably some small VMs doesn't do that either). Don't forget Java runs on a VM, so your code will be transformed in something different according to the VM/OS/HW it runs on.

10

sleep() is a method which is used to hold the process for few seconds or the time you wanted but in case of wait() method thread goes in waiting state and it won’t come back automatically until we call the notify() or notifyAll().

The major difference is that wait() releases the lock or monitor while sleep() doesn’t releases any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution, generally.

Thread.sleep() sends the current thread into the “Not Runnable” state for some amount of time. The thread keeps the monitors it has acquired — i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread.

object.wait() sends the current thread into the “Not Runnable” state, like sleep(), but with a twist. Wait is called on an object, not a thread; we call this object the “lock object.” Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the “wait list” associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.

synchronized(LOCK) {   
   Thread.sleep(1000); // LOCK is held
}

synchronized(LOCK) {   
   LOCK.wait(); // LOCK is not held
}

Let categorize all above points :

Call on:

  • wait(): Call on an object; current thread must synchronize on the lock object.
  • sleep(): Call on a Thread; always currently executing thread.

Synchronized:

  • wait(): when synchronized multiple threads access same Object one by one.
  • sleep(): when synchronized multiple threads wait for sleep over of sleeping thread.

Hold lock:

  • wait(): release the lock for other objects to have chance to execute.
  • sleep(): keep lock for at least t times if timeout specified or somebody interrupt.

Wake-up condition:

  • wait(): until call notify(), notifyAll() from object
  • sleep(): until at least time expire or call interrupt().

Usage:

  • sleep(): for time-synchronization and;
  • wait(): for multi-thread-synchronization.

Ref:diff sleep and wait

10

Wait and sleep are two different things:

  • In sleep() the thread stops working for the specified duration.
  • In wait() the thread stops working until the object being waited-on is notified, generally by other threads.
8
weixin_41568183
零零乙 the two constructs are intended for a different purpose. If you want a thread to stop for a fixed amount of time you use sleep, if you want it to stop until some input comes from the other you use wait/notify. interrupt is intended as a way to signal a thread that it should stop doing what it is doing and terminate. It is handled by sleep, wait but also blocking I/O functions (and you could implement functions with the same behaviour by calling the method Thread.interrupted()). As for the performance, functions are usually optimised for the goal they were designed.
大约 4 年之前 回复
csdnceshi73
喵-见缝插针 So is wait-notify more efficient (low-level) or sleep-interrupt more efficient?
大约 5 年之前 回复
weixin_41568127
?yb? You can of course call wait(long) which will only wait for a given amount of time
大约 10 年之前 回复
csdnceshi67
bug^君 It would be very poor implementation of wait() if it wasted CPU cycles. wait/notify is used quite a lot for interthread communication.
大约 10 年之前 回复
csdnceshi78
程序go - I think it does. It waits() for its chunk of CPU cycles and then the OS gives the CPU cycles to other Threads. I think this might be OS dependant, I am not sure.
大约 10 年之前 回复
csdnceshi67
bug^君 Wait doesn't waste CPU cycles.
大约 10 年之前 回复
csdnceshi78
程序go but you can interrupt a sleeping Thread. In that case wait() is redundant infact it wastes CPU cycles too :-(
大约 10 年之前 回复

You are correct - Sleep() causes that thread to "sleep" and the CPU will go off and process other threads (otherwise known as context switching) wheras I believe Wait keeps the CPU processing the current thread.

We have both because although it may seem sensible to let other people use the CPU while you're not using it, actualy there is an overhead to context switching - depending on how long the sleep is for, it can be more expensive in CPU cycles to switch threads than it is to simply have your thread doing nothing for a few ms.

Also note that sleep forces a context switch.

Also - in general it's not possible to control context switching - during the Wait the OS may (and will for longer waits) choose to process other threads.

8
csdnceshi74
7*4 although sleep does not keep CPU in processing of the current thread, I think, it is anyway a little bit a burden for the CPU, because CPU needs track the moment of when to end the sleep. It does not have that external trigger like "notify" in wait. No?
一年多之前 回复
csdnceshi59
ℙℕℤℝ wait() doesn't keep the CPU processing the current thread. It is like sleep in that it causes a context switch as well: javamex.com/tutorials/threads/context_switch.shtml. I've been asking for half a year all around stackoverflow and it seems like no one knows what's the difference between wait/notify vs sleep/interrupt.
大约 7 年之前 回复

From oracle documentation page on wait() method of Object:

public final void wait()
  1. Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
  2. The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up
  3. interrupts and spurious wakeups are possible
  4. This method should only be called by a thread that is the owner of this object's monitor

This method throws

  1. IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

  2. InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

From oracle documentation page on sleep() method of Thread class:

public static void sleep(long millis)
  1. 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.
  2. The thread does not lose ownership of any monitors.

This method throws:

  1. IllegalArgumentException - if the value of millis is negative

  2. InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Other key difference:

wait() is a non-static method (instance method) unlike static method sleep() (class method).

8
  1. wait() is a method of Object class.
    sleep() is a method of Thread class.

  2. sleep() allows the thread to go to sleep state for x milliseconds.
    When a thread goes into sleep state it doesn’t release the lock.

  3. wait() allows thread to release the lock and goes to suspended state.
    This thread will be active when a notify() or notifAll() method is called for the same object.

7

The methods are used for different things.

Thread.sleep(5000);   // Wait until the time has passed.

Object.wait();        // Wait until some other thread tells me to wake up.

Thread.sleep(n) can be interrupted, but Object.wait() must be notified. It's possible to specify the maximum time to wait: Object.wait(5000) so it would be possible to use wait to, er, sleep but then you have to bother with locks.

Neither of the methods uses the cpu while sleeping/waiting.

The methods are implemented using native code, using similar constructs but not in the same way.

Look for yourself: Is the source code of native methods available? The file /src/share/vm/prims/jvm.cpp is the starting point...

7
csdnceshi69
YaoRaoLov Thread.sleep timing can also be set to indefinite. Object.wait timing can also be set to definite. This answer doesn't explain why we need 2 hammers that do the same thing.
大约 5 年之前 回复
共29条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
线程等待与唤醒
线程等待与唤醒 标签: 多线程 基本方法简介 所有的等待和唤醒线程,都是针对某个具体对象实例的. API接口 说明 wait() 让当前线程进入等待(阻塞)状态,直到其他线程调用此对象的notify()或notifyAll()来唤醒,之后该线程进入就绪状态. wait(long timeout) 让当前线程进入阻塞状态,直到其他线程唤...
Java-时间等待(主线程睡眠)
  Java-时间等待 1 TimeUnit.DAYS.sleep(1);//天 2 TimeUnit.HOURS.sleep(1);//小时 3 TimeUnit.MINUTES.sleep(1);//分 4 TimeUnit.SECONDS.sleep(1);//秒 5 TimeUnit.MILLISECONDS.sleep(1000);//毫秒 6 TimeUnit.MICRO...
java 当前现成等待或睡眠10秒
try{                Thread.currentThread().sleep(5000);             }catch(InterruptedException ie){                 ie.printStackTrace();             }
挂起和阻塞区别?sleep()和wait()的区别?
挂起和阻塞区别: (1)挂起是一种主动行为,因此恢复也应该要主动完成。而阻塞是一种被动行为,是在等待事件或者资源任务的表现,你不知道它什么时候被阻塞,也不清楚它什么时候会恢复阻塞。 (2)阻塞(pend)就是任务释放CPU,其他任务可以运行,一般在等待某种资源或者信号量的时候出现。挂起(suspend)不释放CPU,如果任务优先级高,就永远轮不到其他任务运行。一般挂起用于程序调试中的条件中断,当
阻塞与忙等
当一个进程变为阻塞态时,会交出CPU 当一个进程处于忙等,是在时间片内,进程一直占用CPU,但是并未做有意义的操作
ABAP里面的Sleep函数
wait up to 42 seconds. Does a roll-out and releases the work process to the listener Does an implicit Database commit Use when CPU processes are at a premium and when the implicit commit will...
nodejs中实现sleep功能,暂停几秒.
一 背景 在使用nodejs爬虫的时候,经常会遇到别人的网站对频率的反爬机制, 这个时候如果不做处理程序就会挂掉,重新启动也会继续被屏蔽.这个问题怎么解决呢, 我的想法就是程序暂停10分钟或者更长的时间,继续爬取. 二 方法 其实使用setTimeout就可以实现,只是nodejs异步已经很金字塔了,再加一层会更恐怖,所以 本文使用nodejs的第三方模块async来实现,asyn
nodejs8.0+中实现sleep功能,暂停几秒.
nodejs8.0+中实现sleep功能,暂停几秒.
Windows命令行bat批处理延迟sleep方法
批处理
BAT Sleep等待一段时间
rem 等待10秒 ping本机10次不使用默认的次数,nul是不显示ping信息: @ping -n 10 127.1>nul     bat相关应用: rem 等待10秒 ping本机10次不使用默认的次数,nul是不显示ping信息: @ping -n 30 127.1>nul   rem 启动tomcate bat文件,注意最好放在tomcate bin 目录下,这样能调用st
java基础篇之 休眠(sleep、延时执行)
sleep()使当前线程进入停滞状态(阻塞当前线程),让出CPU的使用、目的是不让当前线程独自霸占该进程所获的CPU资源,以留一定时间给其他线程执行的机会。 import java.util.*; public class SleepDemo { public static void main(String args[]) { try { Syste...
java 中的sleep()和wait() 等的区别和详解
1、sleep()  使当前线程(即调用该方法的线程)暂停执行一段时间,让其他线程有机会继续执行,但它并不释放对象锁。也就是说如果有synchronized同步快,其他线程仍然不能访问共享数据。注意该方法要捕捉异常。 例如有两个线程同时执行(没有synchronized)一个线程优先级为MAX_PRIORITY,另一个为MIN_PRIORITY,如果没有Sleep()方法,只有高优先级的线程执行完
selenium常用的三种等待方式:sleep(),隐性等待,显性等待
1.强制等待 第一种也是最简单粗暴的一种办法就是强制等待sleep(x),强制让闪电侠等x时间 from selenium import webdriver import time # 会开会话 driver = webdriver.Chrome() driver.get('http://www.baidu.com') # 强制等待3秒 time.sleep(3) print(driv...
Windows系统中睡眠和关闭屏幕的异同点
-
待机、休眠、睡眠的区别(整理)
作为一个计算机专业毕业的人,我居然不知道这三者的具体区别是什么太菜了,从网上查了下整理这篇小知识。 电脑闲置的时候,除了关机之外,用户还可以考虑将电脑设为休眠或睡眠状态。与关机相比,系统具有以下休眠和睡眠区别和优点: 1:不需要关闭正在进行的工作,电脑唤醒后,所有打开的程序、窗口马上恢复至休眠或睡眠之前的状态,方便用户继续完成中断的工作。 2:唤醒的速度比开机快都多。正常开机
linux中的不可中断睡眠和可中断睡眠简述
Linux 中的进程睡眠状态有两种:一种是可中断的睡眠状态,其状态标志位为TASK_INTERRUPTIBLE;另一种是不可中断的睡眠状态,其状态标志位为TASK_UNINTERRUPTIBLE。 可中断的睡眠状态的进程会睡眠直到某个条件变为真,如产生一个硬件中断、释放进程正在等待的系统资源或是传递一个信号都可以是唤醒进程的条件。 不可中断睡眠状态与可中断睡眠状态类似,但是它有一个例外,那就是...
通过sleep_for来使线程睡眠一定的时间
#include #include #include using namespace std; int main() {     mutex m;     thread t1([&m]()     {         this_thread::sleep_for(chrono::seconds(10));//通过sleep_for来使线程睡眠一定的时间         f
计算机休眠和睡眠的区别
休眠 休眠模式一般需要点按开机键才能唤醒,有时候也可以通过键盘或者鼠标,比如用支持鼠标或键盘唤醒的主板,休眠唤醒的时间比较长,所以经常让人觉得电脑进入休眠后就无法唤醒,其实大家需要耐心等待一会。 之所以休眠唤醒时间长,主要是因为在休眠的时候,电脑内存中的所有数据全部放到了硬盘中,当按开机键唤醒电脑的时候,电脑又会把这些数据全部恢复到内存里面,然后恢复到休眠前的工作状态,这个时间是比较长的。 休眠...
睡眠排序法-一个不准确的排序方法
今天看到一个非常玄奇的排序方法,大致上类似于桶排序,但是不是特别可靠,就是睡眠排序法,额, 简单的代码如下: from time import sleep items = [2, 4, 10, 2, 1, 7] # 睡眠排序算法 def sleep_sort(i): sleep(i * 0.01) print(i) import threading [threadi...
可中断睡眠 sleep
可中断睡眠 可中断睡眠的执行情况:进程开始时处于可中断睡眠状态;那么如果进程接收到信号后,进程将被唤醒而不在阻塞,当执行完信号处理函数后,就不再睡眠了,直接向下执行代码。 sleep()函数 unsigned int sleep(unsigned int seconds); 注意: 1)能被信号打断,然后处理信号函数以后,就不再睡眠了,直接向下执行代码 2)sleep函数的返回值,是剩余的秒数 代...
阻塞等待和忙等待,以及超时问题
阻塞等待和忙等待的最大区别是是否消耗cpu,在嵌入式中我们常对应的是轮询方式和中断方式,应该十分明确的是,阻塞等待的时候,你已经被挂起,所以是不消耗cpu的,但是我们不可能傻傻的就是为了挂起,只是说我们当前不需要,可以先让别人用,当我们需要的时候,我们还是会要回来的。但是已经阻塞挂起,是如何又可以转换调度状态的那?当然是靠一些操作系统内部的消息机制。对于超时,需要说明的是,我们说阻塞的时候,我们被
偶的第一个blog开张了,希望能好好地用下去
rt
爬虫中的隐式休眠和显示休眠
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC #隐式休眠 #显式休眠 #隐式休眠是全局的,如果找不到等待设置的秒数,...
操作系统睡眠和休眠的区别
之前有待机的说法,现在一般用的是睡眠或者休眠。 睡眠:将计算机当前运行状态(或者说内存状态)完整地保存到磁盘,并且除内存外其他设备均断电,当计算机再次唤醒的时候如果睡眠过程中没有供电故障则直接从内存启动,如果发生了供电故障则先加载保存到磁盘的内存状态文件,然后启动。 休眠:将当前内存状态保存到磁盘,下次唤醒的时候需要先加载这些文件,再启动。相比睡眠相当于睡眠状态下发生了供电故障,然后需要加载磁
Java解惑 - sleep和wait/notify机制, 线程阻塞和等待的区别
sleep()方法sleep()方法是定义在Thread上的native方法, 在设定时间段内(精度取决于CPU)阻塞线程的执行, 但是并不更改线程的锁持有情况.wait/notify机制wait()方法是定义在Object上的方法, 是java语言级的方法, 需要在同步块或者同步方法中进行调用, 会释放锁, 并进入锁对象的等待队列, 需要等到其他线程调用notify()方法释放锁后(实际上该线程
十五.python+selenium之等待时间(三种)
1. 强制等待时间 sleep() : 必须导入time包后才可以使用,强制等待生效时间=页面跳转时间+sleep()设置休眠时间 2.显示等待时间 WebDriverWait() : 必须导入WebDriverWait包才可以使用,显示等待时间是针对单个元素生效的,当在规定时间内找到了对应元素,则执行下一步操作。 3.隐式等待时间 implicitly_wait() : 智能等待时间,是针对...
多线程同步中sleep与wait区别
1、函数 wait是Object的一个函数,指线程处于进入等待状态,此时线程不占用任何资源,不增加时间限制。wait可以被notify和notifyAll函数唤醒(这两个也是Object的函数)。 sleep则是Thread的一个函数,指线程被调用时,占着CPU不工作.此时,系统的CPU部分资源被占用,其他线程无法进入,会增加时间限制。 所以 sleep(100L)意思
Dart 异步编程详解
文章目录Dart 异步编程Dart 的事件循环调度任务延时任务Future 详解创建 Future注册回调async 和 awaitIsolatespawnUrispawn使用场景 Dart 异步编程 编程中的代码执行,通常分为同步与异步两种。简单说,同步就是按照代码的编写顺序,从上到下依次执行,这也是最简单的我们最常接触的一种形式。但是同步代码的缺点也显而易见,如果其中某一行或几行代码非常耗时,...
JS中 实现for循环里面睡眠1秒再执行的相同的效果
实现的效果:每次产生一个随机数,并做相应的动作后,暂停1秒再执行相同的操作,并且可以控制执行的次数 实现的代码如下:      var i=0;      function start (){     /*产生一个0-9的随机数 */          var a=Math.floor(Math.random()*9)+1;     document.getElementById(
linu0.11父进程等待子进程退出和进程退出原理分析
// 释放pcb的一页内存,重新调度进程 void release(struct task_struct * p) { int i; if (!p) return; for (i=1 ; i<NR_TASKS ; i++) if (task[i]==p) { task[i]=NULL; free_page((long)p); schedule(); ...
linux之睡眠函数(my_sleep)
我们在程序中,很多次用到sleep()函数,让它睡眠几秒后再执行该进程。今天呢,我要给大家实现一下sleep函数。 看看代码哦:
EZwait.zip DOS(CMD)窗口和批处理命令如何实现等待(或睡眠)一定时长?小工具EZwait帮到你!目前版本:2
(仅限Windows操作系统,需安装C++环境)平时有没有对于CMD窗口和批处理如何实现等待一定时长的问题感到困扰?我也是。我在网上也看到过类似的问题。有些利用ping,但是这样并不完美,甚至说不算一个方法。于是,我决心研制一款小工具:EZwait(Easy Wait)。在熟悉的DOS黑窗口中就可以使用它。在记事本中编写.bat .cmd批处理文件时也可以使用它。只需要用到一个命令:wait。本程序截止2019/7/29已经有了接近十种功能了:程序当前版本信息显示wait -inf(或-i),程序显示指定版本信息wait -inf(或-i) [版本],等待1秒(1000毫秒)wait,等待指定毫秒数:wait [毫秒数],提示,并等待指定毫秒数:wait -r(或-remind) [毫秒数],提示指定信息,并等待指定毫秒数wait -remindecho(或-R) [提示信息] [毫秒数]。本程序还有复杂的错误报出,查询功能(代码量很多,但智能)wait -error(或-e)报出错误表,wait -error(或-e) [错误的编码]查询某一错误。总之。。。拉风又嚣张! 安装方法在压缩包里! 在最后一版时,我会公开源代码! 对了,其实,是因为我忘记备份1版才没了1版的。。。嘿嘿 copyright 2019 XyloZebra 转载请声明原网址! 我只在csdn发送! 本版本是2版,下一版即将更新内容: 1.wait -help查询指令的帮助(终于不用在简介打那么多字了!) 2.wait -p [毫秒数] 等待一定时间,后暂停(pause) 3.wait -p [毫秒数] [-pf or -wf] 如果-pf,此语句等价上一条。 如果-wf,先暂停,后等待一段时间。
Linux阻塞和非阻塞
阻塞(休眠)调用是没有获得资源则挂起进程,被挂起的进程进入休眠状态,调用的函数只有在得到结果之后才返回,进程继续。非阻塞(休眠)是不能进行设备操作时不挂起,或返回,或反复查询,直到可以进行操作为止,被调用的函数不会阻塞当前进程,而会立刻返回。因为阻塞的进程会进入休眠状态,因此,必须确保有一个地方能够唤醒休眠的进程。唤醒进程的地方最大可能发生在中断里面,因为硬件资源获得的同时往往伴随着一个中断。使用
JS睡眠函数用法
/** 先从正常的延时执行说起,以下代码会在2s后弹出true,OK*/[html] view plain copyfunction st(){         alert(true);  }  setTimeout(st, 2000);  /** 下面的代码也会弹出true,但不OK,因为延时没有起作用*/[html] view plain copyfunction st(arg){      ...
主线程等待10秒钟,无应答返回(一)
  场景需求: 其他应用向我们的应用A发来请求,如果应用A10秒内无处理结果则返回数据未处理完成。工作简化:主线程等待10秒钟,如果子线程没有完成工作,则日志标识。下面是代码实现: import java.util.Random; import java.util.concurrent.Callable; import org.slf4j.Logger; import org.slf...
Windows系统中睡眠、休眠、待机、混合睡眠的解释说明
有时候需要离开电脑,关机之后重新打开计算机又会等很久,如果不关又比较浪费能源,听说Windows系统有睡眠、休眠等功能,它们到底是怎么回事呢?休眠和睡眠,从字面上来讲区别不大,所以常常让很多人很疑惑,这两种状态到底有何不同,它们的优缺点如下:“睡眠”是Windows系统提供的一种节能状态,当用户需要离开电脑的时候,可以在“关机”菜单里面选择这个命令。这样系统将正在处理的...
mac 苹果电脑的睡眠与休眠,决待机耗电的问题,AddressBookSourceSync
前一阵电脑关上盖子任然很费电,于是调查一下, 以下是苹果电脑的几种休眠状态, 查看自己电脑的休眠状态pmset -ghibernatemode=0by default is supported on desktops. The system will not back memory up to persistent storage. The system must wake from the c
信号、信号量、进程的状态的区别你知道吗?
信号量(Semaphore),有时被称为信号灯,是在多环境下使用的一种设施,是可以用来保证两个或多个关键代码段不被并发调用。 在进入一个关键代码段之前,线程必须获取一个信号量;一旦该关键代码段完成了,那么该线程必须释放信号量。其它想进入该关键代码段的线程必须等待直到第一个线程释放信号量。为了完成这个过程,需要创建一个信号量VI,然后将Acquire Semaphore VI以及Release
在Js中使程序睡眠的sleep方法
此函数能使js睡眠,将函数贴到代码中即可使用使用例子:sleep(5000);  //睡眠5秒function sleep(numberMillis) { var now = new Date(); var exitTime = now.getTime() + numberMillis; while (true) { now = new Date(); if (now.getTim...
Python+Selenium 自动化测试 2. Webdriver API介绍
目录 一 Webdriver介绍 二 webdriver实现的原理 三 API介绍 Webdriver 元素的查找的八种方式 find_element_by_id() 源码 find_element_by_name() 源码 find_element_by_link_text() 源码 find_element_by_partial_link_text() 源码 find...