“wait()”和“wait()”之间的区别 与“sleep()”相比 爪哇语

发布于 2024-07-25 12:19:50 字数 252 浏览 5 评论 0 原文

线程中的 wait()sleep() 有什么区别?

我的理解是,wait()-ing 线程仍处于运行模式并使用 CPU 周期,但 sleep()-ing 不消耗任何 CPU 周期,正确吗?

为什么我们同时有 wait()sleep()

它们的实施在较低级别有何不同?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

云胡 2024-08-01 12:19:51

等待和睡眠是两个不同的事情:

  • sleep() 中,线程在指定的时间内停止工作。
  • 在 wait() 中,线程停止工作,直到通知正在等待的对象(通常是由其他线程通知)。

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.
寒冷纷飞旳雪 2024-08-01 12:19:51

sleepThread的方法,waitObject的方法,所以wait/notify< /code> 是一种在 Java 中同步共享数据的技术(使用 monitor),但是 sleep 是线程暂停自身的一种简单方法。

sleep is a method of Thread, wait is a method of Object, so wait/notify is a technique of synchronizing shared data in Java (using monitor), but sleep is a simple method of thread to pause itself.

木有鱼丸 2024-08-01 12:19:51

sleep() 是一种方法,用于将进程保持几秒钟或您想要的时间,但在 wait() 方法线程进入等待状态,直到它不会自动返回我们调用notify()或notifyAll()。

主要区别wait() 释放锁或监视器,而 sleep() 在等待时不会释放任何锁或监视器。 通常,等待用于线程间通信,而睡眠用于引入执行暂停。

Thread.sleep() 将当前线程置于“不可运行”状态一段时间。 线程保留它已获取的监视器 - 即,如果线程当前位于同步块或方法中,则其他线程无法进入此块或方法。 如果另一个线程调用 t.interrupt() 它将唤醒睡眠线程。 请注意,sleep 是一种静态方法,这意味着它始终影响当前线程(正在执行 sleep 方法的线程)。 一个常见的错误是调用 t.sleep(),其中 t 是不同的线程; 即便如此,当前线程将处于休眠状态,而不是 t 线程。

object.wait() 将当前线程发送到“不可运行”状态,类似于 sleep(),但有所不同。 Wait 是在对象上调用的,而不是在线程上调用的; 我们将此对象称为“锁定对象”。 在调用lock.wait()之前,当前线程必须在锁对象上进行同步; wait() 然后释放该锁,并将该线程添加到与该锁关联的“等待列表”中。 稍后,另一个线程可以在同一个锁对象上进行同步并调用lock.notify()。 这会唤醒原来的等待线程。 基本上,wait()/notify()就像sleep()/interrupt(),只是活动线程不需要指向睡眠线程的直接指针,而只需要指向共享锁对象。

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

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

让我们对以上几点进行分类:

Call on:

  • wait(): 调用对象; 当前线程必须在锁对象上同步。
  • sleep(): 在线程上调用; 始终是当前正在执行的线程。

Synchronized:

  • wait():同步时多个线程一一访问同一个Object。
  • sleep():同步时,多个线程等待睡眠线程的睡眠结束。

持有锁:

  • wait():释放锁,让其他对象有机会执行。
  • sleep():如果指定超时或有人中断,则保持锁定至少 t 次。

唤醒条件:

  • wait():直到从对象调用notify()、notifyAll()
  • sleep():直到至少时间到期或调用interrupt()。

用法:

  • sleep(): 用于时间同步;
  • wait():用于多线程同步。

参考:sleep 的区别>等待

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

尸血腥色 2024-08-01 12:19:51

简而言之,wait 是等待直到其他线程调用您,而 sleep 是在某个指定的时间段内“不执行下一条语句”。

而且 sleep 是 Thread 类中的静态方法,它在线程上运行,而 wait() 是在 Object 类中并在对象上调用。

另一点,当您对某个对象调用 wait 时,涉及的线程会同步该对象,然后等待。 :)

In simple words, wait is wait Until some other thread invokes you whereas sleep is "dont execute next statement" for some specified period of time.

Moreover sleep is static method in Thread class and it operates on thread, whereas wait() is in Object class and called on an object.

Another point, when you call wait on some object, the thread involved synchronize the object and then waits. :)

雪落纷纷 2024-08-01 12:19:51

waitsleep 方法非常不同:

  • sleep 无法“唤醒”,
  • wait 有一种方法“在等待期间由另一个线程调用 通知notifyAll

想想看,这些名字在这方面是令人困惑的; 但是 sleep 是一个标准名称,wait 就像 WaitForSingleObjectWaitForMultipleObjects

wait and sleep methods are very different:

  • sleep has no way of "waking-up",
  • whereas wait has a way of "waking-up" during the wait period, by another thread calling notify or notifyAll.

Come to think about it, the names are confusing in that respect; however sleep is a standard name and wait is like the WaitForSingleObject or WaitForMultipleObjects in the Win API.

滴情不沾 2024-08-01 12:19:51

从这篇文章: http://javaconceptoftheday.com/difference- Between-wait-and-sleep-methods-in-java/

wait() 方法。

1)调用wait()方法的线程释放其持有的锁。

2) 在其他线程对同一锁调用notify()或notifyAll()方法后,该线程重新获得锁。

3) wait()方法必须在synchronized块内调用。

4) wait()方法总是在对象上调用。

5) 等待线程可以通过调用notify()或notifyAll()方法被其他线程唤醒。

6) 要调用wait()方法,线程必须拥有对象锁。

sleep() 方法

1) 调用 sleep() 方法的线程不会释放其持有的锁。

2) sleep()方法可以在同步块内部或外部调用。

3) sleep()方法总是在线程上调用。

4) 休眠的线程不能被其他线程唤醒。 如果这样做,线程将抛出 InterruptedException。

5)调用sleep()方法,线程不需要拥有对象锁。

From this post : http://javaconceptoftheday.com/difference-between-wait-and-sleep-methods-in-java/

wait() Method.

1) The thread which calls wait() method releases the lock it holds.

2) The thread regains the lock after other threads call either notify() or notifyAll() methods on the same lock.

3) wait() method must be called within the synchronized block.

4) wait() method is always called on objects.

5) Waiting threads can be woken up by other threads by calling notify() or notifyAll() methods.

6) To call wait() method, thread must have object lock.

sleep() Method

1) The thread which calls sleep() method doesn’t release the lock it holds.

2) sleep() method can be called within or outside the synchronized block.

3) sleep() method is always called on threads.

4) Sleeping threads can not be woken up by other threads. If done so, thread will throw InterruptedException.

5) To call sleep() method, thread need not to have object lock.

夜还是长夜 2024-08-01 12:19:51

这里 wait() 将处于等待状态,直到它被另一个线程通知,但是 sleep() 将有一段时间......之后它会自动转移到就绪状态......

Here wait() will be in the waiting state till it notify by another Thread but where as sleep() will be having some time..after that it will automatically transfer to the Ready state...

少女情怀诗 2024-08-01 12:19:51
  1. wait()Object 类的方法。
    sleep()Thread 类的方法。

  2. sleep() 允许线程进入 sleep 状态 x 毫秒。
    当线程进入睡眠状态时它不会释放锁

  3. wait() 允许线程释放锁并进入挂起状态
    notify()notifAll() 方法被执行时,该线程将处于活动状态
    调用同一个对象。

  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.

独享拥抱 2024-08-01 12:19:51

sleep/interrupt 和 wait/notify 之间的一个潜在的巨大区别是

在不需要的时候生成异常是低效的。 如果线程之间的通信速率很高,那么如果一直调用中断就会产生大量异常,这完全是对 CPU 的浪费。

One potential big difference between sleep/interrupt and wait/notify is that

Generating an exception when not needed is inefficient. If you have threads communicating with each other at a high rate, then it would be generating a lot of exceptions if you were calling interrupt all the time, which is a total waste of CPU.

我要还你自由 2024-08-01 12:19:51

你是对的 - Sleep() 会导致该线程“睡眠”,CPU 将关闭并处理其他线程(也称为上下文切换),而我相信 Wait 会让 CPU 处理当前线程。

我们两者都有,因为尽管在您不使用 CPU 时让其他人使用 CPU 似乎是明智的,但实际上上下文切换会产生开销 - 取决于睡眠时间的长短,CPU 周期的成本可能更高切换线程而不是简单地让线程在几毫秒内不执行任何操作。

另请注意,睡眠会强制进行上下文切换。

另外 - 一般来说,不可能控制上下文切换 - 在等待期间,操作系统可能(并且将等待更长的时间)选择处理其他线程。

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.

任谁 2024-08-01 12:19:51

这些方法用于不同的事情。

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

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

Thread.sleep(n)可以被中断,但Object.wait()必须被通知。
可以指定等待的最长时间:Object.wait(5000),因此可以使用wait来,呃,睡眠但这样你就必须费心去锁了。

这两种方法在睡眠/等待时都不使用CPU。

这些方法是使用本机代码实现的,使用类似的构造,但方式不同。

自己查找:是否有原生方法的源代码? 文件 /src/share/vm/prims/jvm.cpp 是起点...

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...

幽梦紫曦~ 2024-08-01 12:19:51

wait() 和 sleep() 的区别?

线程.sleep()
一旦它的工作完成,那么只有它才将锁释放给每个人。 直到它永远不会向任何人释放锁。

  Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.

对象.wait()
当进入等待阶段时,将释放按键并根据参数等待一些秒数。

例如:

你正在右手拿咖啡,你可以拿同一只手的另一个人,什么时候你放下然后只拿另一个相同类型的物体。 还。 这是睡眠()
你睡觉的时候你没有做任何工作,你只是在睡觉..这里也一样。

等待()。 当你被放下并采取另一个意思是在你等待的时候,那就是等待

你正在播放电影或你系统中的任何东西,就像播放器一样,你不能一次播放多个,对吧,那就是它在这里,当你关闭并选择另一个人的电影或歌曲,同时称为等待

Wait() and sleep() Differences?

Thread.sleep()
Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.

  Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.

Object.wait()
When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.

For Example:

you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep()
you sleep time you didn't any work, you are doing only sleeping.. same here also.

wait(). when you are put down and take another one mean while you are waiting , that's wait

you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait

又怨 2024-08-01 12:19:51

wait 释放锁,而 sleep 则不会。 一旦调用 notifynotifyAll ,处于等待状态的线程就有资格被唤醒。 但在睡眠的情况下,线程会保持锁定,并且只有在睡眠时间结束后才符合资格。

wait releases the lock and sleep doesn't. A thread in waiting state is eligible for waking up as soon as notify or notifyAll is called. But in case of sleep the thread keeps the lock and it'll only be eligible once the sleep time is over.

挖鼻大婶 2024-08-01 12:19:51

sleep() 方法使当前线程从运行状态转变为阻塞状态指定的时间。 如果当前线程拥有任何对象的锁,那么它会一直持有该对象,这意味着其他线程无法执行该类对象中的任何同步方法。

wait()方法使当前线程进入阻塞状态,要么持续指定的时间,要么直到notify,但在这种情况下该线程释放了该对象的锁(这意味着其他线程可以执行任何调用对象的同步方法。

sleep() method causes the current thread to move from running state to block state for a specified time. If the current thread has the lock of any object then it keeps holding it, which means that other threads cannot execute any synchronized method in that class object.

wait() method causes the current thread to go into block state either for a specified time or until notify, but in this case the thread releases the lock of the object (which means that other threads can execute any synchronized methods of the calling object.

吃颗糖壮壮胆 2024-08-01 12:19:51

在我看来,两种机制之间的主要区别在于睡眠/中断是处理线程的最基本方式,而等待/通知是一种抽象,旨在更容易地进行线程间通信。这意味着睡眠/中断可以做任何事情,但是这个特定的任务更难完成。

为什么wait/notify更合适? 以下是一些个人注意事项:

  1. 它强制集中化。它允许使用单个共享对象协调一组线程之间的通信。 这大大简化了工作。

  2. 它强制同步。因为它使程序员将等待/通知的调用包装在同步块中。

  3. 它与线程来源和数量无关。通过这种方法,您可以任意添加更多线程,而无需编辑其他线程或跟踪现有线程。 如果您使用睡眠/中断,首先您需要保留对睡眠线程的引用,然后手动一一中断它们。

现实生活中的一个例子可以很好地解释这一点,那就是一家经典餐厅以及员工之间沟通的方法:服务员将顾客的要求放在一个中心位置(软木板、桌子等),按一下铃,厨房的工作人员就会过来接受这样的要求。 一旦菜品准备好,厨房工作人员就会再次按铃,以便服务员知道并把菜品带到顾客面前。

In my opinion, the main difference between both mechanisms is that sleep/interrupt is the most basic way of handling threads, whereas wait/notify is an abstraction aimed to do thread inter-communication easier. This means that sleep/interrupt can do anything, but that this specific task is harder to do.

Why is wait/notify more suitable? Here are some personal considerations:

  1. It enforces centralization. It allows to coordinate the communication between a group of threads with a single shared object. This simplifies the work a lot.

  2. It enforces synchronization. Because it makes the programmer wrap the call to wait/notify in a synchronized block.

  3. It's independent of the thread origin and number. With this approach you can add more threads arbitrarily without editing the other threads or keeping a track of the existing ones. If you used sleep/interrupt, first you would need to keep the references to the sleeping threads, and then interrupt them one by one, by hand.

An example from the real life that is good to explain this is a classic restaurant and the method that the personnel use to communicate among them: The waiters leave the customer requests in a central place (a cork board, a table, etc.), ring a bell, and the workers from the kitchen come to take such requests. Once that there is any course ready, the kitchen personnel ring the bell again so that the waiters are aware and take them to the customers.

琉璃梦幻 2024-08-01 12:19:51

关于 sleep 不释放锁而 wait 释放锁的示例

这里有两个类:

  1. Main :包含 main 方法和两个线程。
  2. Singleton:这是一个单例类,有两个静态方法 getInstance() 和 getInstance(boolean isWait)。

    公共类主要{ 
    
      私有静态单例 singletonA = null; 
      私有静态单例 singletonB = null; 
    
      公共静态无效主(字符串[] args)抛出InterruptedException { 
    
      线程 threadA = new Thread() { 
          @覆盖 
          公共无效运行(){ 
    
              singletonA = Singleton.getInstance(true); 
    
          } 
      }; 
    
      线程 threadB = new Thread() { 
          @覆盖 
          公共无效运行(){ 
              singletonB = Singleton.getInstance(); 
    
              while (singletonA == null) { 
                  System.out.println("SingletonA 仍然为空"); 
              } 
    
              if (singletonA == singletonB) { 
                  System.out.println("两个单例是相同的"); 
              } 别的 { 
                  System.out.println("两个单例不相同"); 
              } 
    
          } 
      }; 
    
      threadA.start(); 
      threadB.start(); 
    
       } 
      } 
      

现在

public class Singleton {

    private static Singleton _instance;

    public static Singleton getInstance() {

    if (_instance == null) {
        synchronized (Singleton.class) {
            if (_instance == null)
                _instance = new Singleton();
        }
    }
    return _instance;

}

public static Singleton getInstance(boolean isWait) {

    if (_instance == null) {
        synchronized (Singleton.class) {
            if (_instance == null) {
                if (isWait) {
                    try {
                        // Singleton.class.wait(500);//Using wait
                        Thread.sleep(500);// Using Sleep
                        System.out.println("_instance :"
                                + String.valueOf(_instance));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                _instance = new Singleton();
            }
        }
    }
    return _instance;

 }
}

运行这个示例,您将得到以下输出:

_instance :null
Both singleton are same

这里由 threadA 和 threadB 创建的 Singleton 实例是相同的。 这意味着 threadB 正在外面等待,直到 threadA 释放它的锁。

现在通过注释 Thread.sleep(500); 来更改 Singleton.java; 方法并取消注释 Singleton.class.wait(500); 。 这里因为 Singleton.class.wait(500); 方法threadA将释放所有获取锁并进入“不可运行”状态,threadB将获得更改进入同步块。

现在再次运行:

SingletonA still null
SingletonA still null
SingletonA still null
_instance :com.omt.sleepwait.Singleton@10c042ab
SingletonA still null
SingletonA still null
SingletonA still null
Both singleton are not same

这里由线程 A 和线程 B 创建的 Singleton 实例不相同,因为线程 B 进行了更改以进入同步块,并且在 500 毫秒后,线程 A 从它的最后位置开始并创建了另一个 Singleton 对象。

Example about sleep doesn’t release lock and wait does

Here there are two classes :

  1. Main : Contains main method and two threads.
  2. Singleton : This is singleton class with two static methods getInstance() and getInstance(boolean isWait).

    public class Main {
    
    private static Singleton singletonA = null;
    private static Singleton singletonB = null;
    
    public static void main(String[] args) throws InterruptedException {
    
    Thread threadA = new Thread() {
        @Override
        public void run() {
    
            singletonA = Singleton.getInstance(true);
    
        }
    };
    
    Thread threadB = new Thread() {
        @Override
        public void run() {
            singletonB = Singleton.getInstance();
    
            while (singletonA == null) {
                System.out.println("SingletonA still null");
            }
    
            if (singletonA == singletonB) {
                System.out.println("Both singleton are same");
            } else {
                System.out.println("Both singleton are not same");
            }
    
        }
    };
    
    threadA.start();
    threadB.start();
    
     }
    }
    

and

public class Singleton {

    private static Singleton _instance;

    public static Singleton getInstance() {

    if (_instance == null) {
        synchronized (Singleton.class) {
            if (_instance == null)
                _instance = new Singleton();
        }
    }
    return _instance;

}

public static Singleton getInstance(boolean isWait) {

    if (_instance == null) {
        synchronized (Singleton.class) {
            if (_instance == null) {
                if (isWait) {
                    try {
                        // Singleton.class.wait(500);//Using wait
                        Thread.sleep(500);// Using Sleep
                        System.out.println("_instance :"
                                + String.valueOf(_instance));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                _instance = new Singleton();
            }
        }
    }
    return _instance;

 }
}

Now run this example you will get below output :

_instance :null
Both singleton are same

Here Singleton instances created by threadA and threadB are same. It means threadB is waiting outside until threadA release it’s lock.

Now change the Singleton.java by commenting Thread.sleep(500); method and uncommenting Singleton.class.wait(500); . Here because of Singleton.class.wait(500); method threadA will release all acquire locks and moves into the “Non Runnable” state, threadB will get change to enter in synchronized block.

Now run again :

SingletonA still null
SingletonA still null
SingletonA still null
_instance :com.omt.sleepwait.Singleton@10c042ab
SingletonA still null
SingletonA still null
SingletonA still null
Both singleton are not same

Here Singleton instances created by threadA and threadB are NOT same because of threadB got change to enter in synchronised block and after 500 milliseconds threadA started from it’s last position and created one more Singleton object.

花海 2024-08-01 12:19:51

应该从同步块调用: wait()方法总是从同步块调用,即wait()方法需要在对象之前锁定对象监视器它被称为。 但是 sleep() 方法可以从外部同步块调用,即 sleep() 方法不需要任何对象监视器。

IllegalMonitorStateException :如果在没有获取对象锁的情况下调用wait()方法,则在运行时抛出IllegalMonitorStateException,但sleep() 方法永远不会抛出此类异常。

属于哪个类: wait()方法属于java.lang.Object类,但sleep()方法属于属于java.lang.Thread类。

在对象或线程上调用: wait() 方法在对象上调用,但 sleep() 方法在线程而不是对象上调用。

线程状态:当对象调用wait()方法时,持有对象监视器的线程从运行状态进入等待状态,只有在notify时才能返回到可运行状态()notifyAll() 方法在该对象上被调用。 随后线程调度程序调度该线程从可运行状态进入运行状态。
当在线程上调用 sleep() 时,它会从运行状态进入等待状态,并在睡眠时间结束时返回到可运行状态。

当从同步块调用时:当调用wait()方法时,线程离开对象锁。 但是从同步块或方法线程调用 sleep() 方法时,不会留下对象锁。

更多参考

Should be called from synchronized block : wait() method is always called from synchronized block i.e. wait() method needs to lock object monitor before object on which it is called. But sleep() method can be called from outside synchronized block i.e. sleep() method doesn’t need any object monitor.

IllegalMonitorStateException : if wait() method is called without acquiring object lock than IllegalMonitorStateException is thrown at runtime, but sleep() method never throws such exception.

Belongs to which class : wait() method belongs to java.lang.Object class but sleep() method belongs to java.lang.Thread class.

Called on object or thread : wait() method is called on objects but sleep() method is called on Threads not objects.

Thread state : when wait() method is called on object, thread that holded object’s monitor goes from running to waiting state and can return to runnable state only when notify() or notifyAll() method is called on that object. And later thread scheduler schedules that thread to go from from runnable to running state.
when sleep() is called on thread it goes from running to waiting state and can return to runnable state when sleep time is up.

When called from synchronized block : when wait() method is called thread leaves the object lock. But sleep() method when called from synchronized block or method thread doesn’t leaves object lock.

For More Reference

草莓味的萝莉 2024-08-01 12:19:51

wait() 在同步方法中给出
sleep() 是在非同步方法内给出的,因为 wait() 方法释放了对象上的锁,但 sleep() 或 < code>yield() 确实释放了lock()

wait() is given inside a synchronized method
whereas sleep() is given inside a non-synchronized method because wait() method release the lock on the object but sleep() or yield() does release the lock().

许久 2024-08-01 12:19:51

来自 Oracle 文档页面 wait()< Object 的 /a> 方法:

public final void wait()
  1. 导致当前线程等待,直到另一个线程调用 notify() 方法或 notifyAll() 方法这个物体。 换句话说,此方法的行为与仅执行调用 wait(0) 完全相同。
  2. 当前线程必须拥有该对象的监视器。 线程释放此监视器的所有权并等待,直到另一个线程通知在此对象监视器上等待的线程唤醒中断
  3. ,并且可能出现虚假唤醒
  4. 此方法只能由作为该对象监视器所有者的线程调用

此方法抛出

  1. IllegalMonitorStateException - 如果当前线程不是对象监视器的所有者。

  2. InterruptedException - 如果任何线程在当前线程等待通知之前或期间中断了当前线程。 当抛出此异常时,当前线程的中断状态将被清除。

来自 Oracle 文档页面 sleep() Thread 类的 方法:

public static void sleep(long millis)
  1. 使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。
  2. 线程不会失去任何监视器的所有权。

此方法抛出:

  1. IllegalArgumentException - 如果 millis 的值为负

  2. InterruptedException - 如果任何线程中断了当前线程。 当抛出此异常时,当前线程的中断状态将被清除。

其他关键区别:

wait() 是一个非静态方法(实例方法),与静态方法 sleep() (类方法)不同。

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).

沒落の蓅哖 2024-08-01 12:19:51
  • 方法 wait(1000) 导致当前线程休眠最多一秒
  • 调用 < code>sleep(1000) 使当前线程休眠正好 1 秒
    • 此外,睡眠线程不会锁定任何资源。 但等待线程确实如此。
  • The method wait(1000) causes the current thread to sleep up to one second.
    • A thread could sleep less than 1 second if it receives the notify() or notifyAll() method call.
  • The call to sleep(1000) causes the current thread to sleep for exactly 1 second.
    • Also sleeping thread doesn't hold lock any resource. But waiting thread does.
西瓜 2024-08-01 12:19:51

实际上,所有这些在 Java 文档中都有清楚的描述(但我在阅读答案后才意识到这一点)。

http://docs.oracle.com/javase/8/docs/api /index.html :

wait() - 当前线程必须拥有该对象的监视器。 线程释放
该监视器的所有权并等待另一个线程通知
在此对象的监视器上等待通过以下方式唤醒的线程
调用notify方法或notifyAll方法。 然后线程
等待直到它可以重新获得监视器的所有权并恢复执行。

sleep() - 使当前正在执行的线程休眠(暂时停止执行)指定的毫秒数,具体取决于系统计时器和调度程序的精度和准确性。 该线程不会失去任何监视器的所有权。

Actually, all this is clearly described in Java docs (but I realized this only after reading the answers).

http://docs.oracle.com/javase/8/docs/api/index.html :

wait() - 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 either through a
call to the notify method or the notifyAll method. The thread then
waits until it can re-obtain ownership of the monitor and resumes execution.

sleep() - 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.

青柠芒果 2024-08-01 12:19:50

wait 可以被调用 notify 在正在等待的监视器上,而 <代码>睡眠不能。 此外,wait(和notify)必须发生在监视器对象上的synchronized块中,而sleep则不会:

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

此时,当前正在执行的线程等待并释放监视器。 另一个线程可能会这样做

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

(在同一个 mon 对象上),并且第一个线程(假设它是在监视器上等待的唯一线程)将被唤醒。

您还可以调用 notifyAll 如果多个线程正在监视器上等待 - 这将唤醒所有线程。 然而,只有一个线程能够获取监视器(请记住,wait 位于 synchronized 块中)并继续执行 - 其他线程将被阻塞,直到他们可以获得监视器的锁。

另一点是您在 Object 本身(即,您在对象的监视器上等待),而您在 线程

还有一点是,您可能会从 wait 中获得虚假唤醒(即正在等待的线程无明显原因地恢复)。 在某些条件下旋转时,您应该始终等待,如下所示:

synchronized {
    while (!condition) { mon.wait(); }
}

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(); }
}
不知所踪 2024-08-01 12:19:50

尚未提及的一个关键区别是:

  • sleep() 确实释放它在线程上持有的锁,

    同步(锁定){ 
          线程睡眠(1000);   // 锁被持有 
      } 
      
  • wait() 释放它在对象上持有的锁定。

    <前><代码>同步(锁定){
    LOCK.wait(); // 锁未被持有
    }

One key difference not yet mentioned is that:

  • sleep() does not release the lock it holds on the Thread,

    synchronized(LOCK) {
        Thread.sleep(1000); // LOCK is held
    }
    
  • wait() releases the lock it holds on the object.

     synchronized(LOCK) {
         LOCK.wait(); // LOCK is not held
     }
    
假情假意假温柔 2024-08-01 12:19:50

我发现这个帖子有帮助。 它以人性化的方式表达了 Thread.sleep()、Thread.yield() 和 Object.wait() 之间的区别。 去引用:

这一切最终都会进入操作系统的调度程序,该调度程序
向进程和线程分发时间片。

sleep(n)“我已经完成了我的时间片,请不要给我
另一个至少 n 毫秒。”
操作系统甚至不会尝试
调度休眠线程,直到请求的时间过去。

yield()“我已经完成了我的时间片,但我还有工作要做
操作系统可以立即给线程另一个时间片,
或者给其他线程或处理CPU让出线程
就放弃了。

wait() 表示“我已经完成了我的时间片。 别给我另一个
时间片,直到有人调用notify()。”
sleep()一样,操作系统不会
甚至尝试安排您的任务,除非有人调用 notify() (或其中之一
发生一些其他唤醒情况)。

线程在执行时也会丢失剩余的时间片
阻塞 IO 以及其他一些情况。 如果一个线程工作
在整个时间片中,操作系统强制控制,大致如下
如果yield()被调用,那么其他进程就可以运行。

您很少需要 yield(),但如果您有一个计算量大的应用程序
逻辑任务边界,插入 yield() 可能 改进系统
响应能力(以时间为代价——上下文切换,即使只是
到操作系统并返回,不是免费的)。 根据您的目标进行衡量和测试
一如既往地关心。

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.

执手闯天涯 2024-08-01 12:19:50

这里有很多答案,但我找不到其中提到的语义区别。

这与线程本身无关;而是与线程本身有关。 这两种方法都是必需的,因为它们支持非常不同的用例。

sleep() 让线程像以前一样进入睡眠状态,它只是打包上下文并在预定义的时间内停止执行。 因此,为了在规定时间之前唤醒它,您需要知道线程引用。 这在多线程环境中并不常见。 它主要用于时间同步(例如在 3.5 秒内唤醒)和/或硬编码公平性(只是休眠一段时间并让其他线程工作)。

相反,wait() 是一种线程(或消息)同步机制,允许您通知您没有存储引用(也不关心)的线程。 您可以将其视为发布-订阅模式(wait == 订阅且 notify() == 发布)。 基本上使用notify()你正在发送一条消息(甚至可能根本没有收到,通常你不关心)。

总而言之,通常使用 sleep() 进行时间同步,使用 wait() 进行多线程同步。

它们可以在底层操作系统中以相同的方式实现,或者根本不实现(因为以前版本的 Java 没有真正的多线程;可能一些小型 VM 也不会这样做)。 不要忘记 Java 在虚拟机上运行,​​因此您的代码将根据其运行的虚拟机/操作系统/硬件而转换为不同的内容。

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.

℡寂寞咖啡 2024-08-01 12:19:50

在这里,我列出了 wait()sleep() 方法之间的一些重要区别。
PS: 还可以单击链接查看库代码(内部工作,只需稍微尝试一下即可更好地理解)。

等待()

  1. wait() 方法释放锁。
  2. wait()Object类的方法。
  3. wait() 是非静态方法 - public final void wait() throws InterruptedException { //...}
  4. wait() 应通过 notify()notifyAll() 方法进行通知。
  5. wait() 方法需要从循环中调用,以处理误报。

  6. wait()方法必须从同步上下文(即同步方法或同步块)调用,否则会抛出IllegalMonitorStateException

sleep()

  1. sleep()< /code> 方法不会释放锁。
  2. sleep()java.lang.Thread类的方法。
  3. sleep() 是静态方法 - public static void sleep(long millis, int nanos)
  4. 在指定时间后抛出 InterruptedException { //... },< code>sleep() 已完成。
  5. sleep() 最好不要从循环中调用(即参见下面的代码)。
  6. sleep() 可以从任何地方调用。 没有具体要求。

Ref: 等待和睡眠之间的区别

调用等待和睡眠方法的代码片段

synchronized(monitor){
    while(condition == true){ 
        monitor.wait()  //releases monitor lock
    }

    Thread.sleep(100); //puts current thread on Sleep    
}

线程转换到不同的线程状态

Here, I have listed few important differences between wait() and sleep() methods.
PS: Also click on the links to see library code (internal working, just play around a bit for better understanding).

wait()

  1. wait() method releases the lock.
  2. wait() is the method of Object class.
  3. wait() is the non-static method - public final void wait() throws InterruptedException { //...}
  4. wait() should be notified by notify() or notifyAll() methods.
  5. wait() method needs to be called from a loop in order to deal with false alarm.

  6. wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

sleep()

  1. sleep() method doesn't release the lock.
  2. sleep() is the method of java.lang.Thread class.
  3. sleep() is the static method - public static void sleep(long millis, int nanos) throws InterruptedException { //... }
  4. after the specified amount of time, sleep() is completed.
  5. sleep() better not to call from loop(i.e. see code below).
  6. sleep() may be called from anywhere. there is no specific requirement.

Ref: Difference between Wait and Sleep

Code snippet for calling wait and sleep method

synchronized(monitor){
    while(condition == true){ 
        monitor.wait()  //releases monitor lock
    }

    Thread.sleep(100); //puts current thread on Sleep    
}

thread transition to different thread states

痴情换悲伤 2024-08-01 12:19:50

wait() 和 sleep() 之间的区别

  • 根本区别在于 wait()Object 的非静态方法,而 sleep() 是一个Thread 的静态方法。
  • 主要区别在于 wait() 会释放锁,而 sleep() 在等待时不会释放任何锁。
  • 通常,wait() 用于线程间通信,而 sleep() 用于引入执行暂停。
  • wait() 应该从同步内部调用,否则我们会得到 IllegalMonitorStateException,而 sleep() 可以在任何地方调用。
  • 要从 wait() 再次启动线程,您必须无限期地调用 notify()notifyAll()。 至于sleep(),线程在指定的时间间隔后肯定会启动。

相似之处

  • 两者都会使当前线程进入不可运行状态。
  • 两者都是本机方法。

Difference between wait() and sleep()

  • The fundamental difference is that wait() is non static method of Object and sleep() is a static method of Thread.
  • The major difference is that wait() releases the lock while sleep() doesn’t release any lock while waiting.
  • wait() is used for inter-thread communication while sleep() is used to introduce a pause on execution, generally.
  • wait() should be called from inside synchronise or else we get an IllegalMonitorStateException, while sleep() can be called anywhere.
  • To start a thread again from wait(), you have to call notify() or notifyAll() indefinitely. As for sleep(), the thread gets started definitely after a specified time interval.

Similarities

  • Both make the current thread go into the Not Runnable state.
  • Both are native methods.
夜司空 2024-08-01 12:19:50

在处理 wait 和 sleep 后,我总结出一些不同的要点,首先看一下使用 wait() 和 sleep() 的示例:

示例 1:使用 wait()和睡眠():

synchronized(HandObject) {
    while(isHandFree() == false) {
        /* Hand is still busy on happy coding or something else, please wait */
        HandObject.wait();
    }
}

/* Get lock ^^, It is my turn, take a cup beer now */
while (beerIsAvailable() == false) {
    /* Beer is still coming, not available, Hand still hold glass to get beer,
       don't release hand to perform other task */
    Thread.sleep(5000);
}

/* Enjoy my beer now ^^ */
drinkBeers();

/* I have drink enough, now hand can continue with other task: continue coding */
setHandFreeState(true);
synchronized(HandObject) {
    HandObject.notifyAll();
}

让我们澄清一些关键注意事项:

  1. 调用
    • wait():调用当前持有 HandObject 对象的线程
    • sleep():调用线程执行任务获取啤酒(是类方法,因此会影响当前正在运行的线程)
  2. 同步
    • wait():当同步多线程访问同一个对象(HandObject)时(当多个线程之间需要通信(线程执行编码、线程执行获取啤酒)访问同一个对象 HandObject 时)
    • sleep():等待条件继续执行时(等待啤酒可用)
  3. 保持锁定
    • wait():释放锁,让其他对象有机会执行(HandObject是空闲的,你可以做其他工作)
    • sleep():保持锁定至少t次(或直到中断)(我的工作还没有完成,我继续保持锁定并等待某些条件继续)
  4. 唤醒条件
    • wait():直到从对象调用notify()、notifyAll()
    • sleep():至少直到时间到期或调用中断
  5. 最后一点是使用何时 as estani 表示:

通常使用 sleep() 进行时间同步,使用 wait() 进行时间同步
多线程同步。

如果我错了,请纠正我。

There are some difference key notes i conclude after working on wait and sleep, first take a look on sample using wait() and sleep():

Example1: using wait() and sleep():

synchronized(HandObject) {
    while(isHandFree() == false) {
        /* Hand is still busy on happy coding or something else, please wait */
        HandObject.wait();
    }
}

/* Get lock ^^, It is my turn, take a cup beer now */
while (beerIsAvailable() == false) {
    /* Beer is still coming, not available, Hand still hold glass to get beer,
       don't release hand to perform other task */
    Thread.sleep(5000);
}

/* Enjoy my beer now ^^ */
drinkBeers();

/* I have drink enough, now hand can continue with other task: continue coding */
setHandFreeState(true);
synchronized(HandObject) {
    HandObject.notifyAll();
}

Let clarity some key notes:

  1. Call on:
    • wait(): Call on current thread that hold HandObject Object
    • sleep(): Call on Thread execute task get beer (is class method so affect on current running thread)
  2. Synchronized:
    • wait(): when synchronized multi thread access same Object (HandObject) (When need communication between more than one thread (thread execute coding, thread execute get beer) access on same object HandObject )
    • sleep(): when waiting condition to continue execute (Waiting beer available)
  3. Hold lock:
    • wait(): release the lock for other object have chance to execute (HandObject is free, you can do other job)
    • sleep(): keep lock for at least t times (or until interrupt) (My job still not finish, i'm continue hold lock and waiting some condition to continue)
  4. Wake-up condition:
    • wait(): until call notify(), notifyAll() from object
    • sleep(): until at least time expire or call interrupt
  5. And the last point is use when as estani indicate:

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

Please correct me if i'm wrong.

柒七 2024-08-01 12:19:50

这是一个非常简单的问题,因为这两种方法都有完全不同的用途。

主要区别是等待释放锁或监视器,而睡眠在等待时不会释放任何锁或监视器。 等待用于线程间通信,而睡眠用于引入执行暂停。

这只是一个清晰且基本的解释,如果您想要更多内容,请继续阅读。

如果使用 wait() 方法,线程将进入等待状态,直到我们调用 notify() 方法(或 notifyAll()) 如果您有多个线程处于等待状态并且您想要唤醒所有这些线程)。 并且您需要同步或对象锁或类锁才能访问 wait()notify()notifyAll() 方法。 另一件事是,wait() 方法用于线程间通信,因为如果一个线程进入等待状态,您将需要另一个线程来唤醒该线程。

但在 sleep() 的情况下,这是一种用于将进程保持几秒钟或您想要的时间的方法。 因为您不需要激发任何 notify()notifyAll() 方法来恢复该线程。 或者您不需要任何其他线程来回调该线程。 例如,如果您希望在几秒钟后发生某些事情,就像在游戏中,在用户轮到您后,您希望用户等到计算机开始玩,那么您可以提到 sleep() 方法。

还有一个在面试中经常被问到的更重要的区别:sleep() 属于 Thread 类,wait() 属于 Object类。

这些都是sleep()wait()之间的区别。

这两种方法之间有一个相似之处:它们都是检查语句,因此您需要 try catch 或 throws 来访问这些方法。

我希望这能帮到您。

This is a very simple question, because both these methods have a totally different use.

The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

This was just a clear and basic explanation, if you want more than that then continue reading.

In case of wait() method thread goes in waiting state and it won't come back automatically until we call the notify() method (or notifyAll() if you have more then one thread in waiting state and you want to wake all of those thread). And you need synchronized or object lock or class lock to access the wait() or notify() or notifyAll() methods. And one more thing, the wait() method is used for inter-thread communication because if a thread goes in waiting state you'll need another thread to wake that thread.

But in case of sleep() this is a method which is used to hold the process for few seconds or the time you wanted. Because you don't need to provoke any notify() or notifyAll() method to get that thread back. Or you don't need any other thread to call back that thread. Like if you want something should happen after few seconds like in a game after user's turn you want the user to wait until the computer plays then you can mention the sleep() method.

And one more important difference which is asked often in interviews: sleep() belongs to Thread class and wait() belongs to Object class.

These are all the differences between sleep() and wait().

And there is a similarity between both methods: they both are checked statement so you need try catch or throws to access these methods.

I hope this will help you.

潜移默化 2024-08-01 12:19:50

来源:http://www.jguru.com/faq/view.jsp?EID =47127

线程.sleep() 将当前线程发送到“不可运行”状态
持续一段时间。 线程保留它已获取的监视器
-- 即,如果线程当前位于同步块或方法中,则其他线程不能进入该块或方法。 如果另一个线程调用 t.interrupt()它将唤醒休眠的线程。

注意sleep是一个静态方法,这意味着它总是影响
当前线程(正在执行 sleep 方法的线程)。 A
常见的错误是调用 t.sleep() ,其中 t 是不同的线程;
即使这样,休眠的也是当前线程,而不是 t 线程。

t .suspend() 已弃用。 使用它可以停止其他线程
比当前线程。 挂起的线程保留其所有监视器并
由于此状态不可中断,因此很容易出现死锁。

对象.wait() 将当前线程发送到“Not Runnable”状态,
sleep() 类似,但有所不同。 Wait 是在对象上调用的,而不是在
线; 我们将此对象称为“锁定对象”。 在 lock.wait() 之前
调用时,当前线程必须在锁对象上进行同步; 等待()
然后释放该锁,并将该线程添加到“等待列表”中
与锁相关联。 稍后,另一个线程可以在
相同的锁定对象并调用lock.notify()。 这唤醒了原来的,
等待线程。 基本上,wait()/notify()就像
sleep()/interrupt(),只有活动线程不需要直接
指向休眠线程的指针,但仅指向共享锁对象。

source : http://www.jguru.com/faq/view.jsp?EID=47127

Thread.sleep() sends the current thread into the "Not Runnable" state
for some amount of time. The thread keeps the monitors it has aquired
-- 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.

t.suspend() is deprecated. Using it is possible to halt a thread other
than the current thread. A suspended thread keeps all its monitors and
since this state is not interruptable it is deadlock prone.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文