Difference betn  wait() and sleep() method of a thread

Can anyone briefly differentiate between the sleep() and wait() method of a thread.

[url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Thread.html#sleep(long)]sleep
[url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#wait()]wait

Similar Messages

  • Difference between wait() and sleep()

    hi
    can any one tell me what is the difference between wait() and sleep().
    thanks in advance.

    Mahaboob,
    This question has been asked before; however, I will give you a real life example.
    Imagine you are in a super market and you go to the till to pay by your card, then behind you there are 10 people waiting in queue. You card does not work since you have not supplied the right pin code; there are two option
    1- Sleep
    2- Wait
    1- If you sleep you will lock the till for your self and try to figure out the pin number while the queue behind you increase on the resource (till)
    so you are engaging the till and wasting its time and wasting the till machine resource (CPU)
    2- you are polite, you move aside and wait so so that others can use the resource (till) until somebody in the queue finishes ( a good person) and give you a shout to tell you come in to the till to process your payment; you wake up and enter the pin number and go out from the super market.
    Now when you sleep, the current thread locks the resource so no body can use it and wast the CPU time
    while wait make the current thread release the lock on the object and does not ( this thread) actually wast the CPU time
    There are much more explanantion, try to search this forum.
    Regards,
    Alan Mehio
    London,UK

  • What's the difference between equals() and compareTo() method

    I'm confused between the two method from String class ,,, what's the main difference between equals() and compareTo() method?

    API docs give quite clear information IMHO
    public boolean equals(Object anObject)
    Compares this string to the specified object. The result is true if and only if the argument is not null and is
    a String object that represents the same sequence of characters as this object.
    public int compareTo(String anotherString)
    Compares two strings lexicographically. ....
    The result is a negative integer if this String object lexicographically precedes the argument string. The
    result is a positive integer if this String object lexicographically follows the argument string. The result is
    zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return
    true. Mike

  • BDC - Difference bw Transaction and Batch method

    Hi
    How we can handle the error messages in transaction and batch method?.
    Regards
    Nikhil V Kumar

    hi Nikhil,
    WELCOME TO SDN
       these are some of the differences between the two
    The major differences between Session method and Call transaction are as follows:
    <b>SESSION METHOD</b>               
    1.Data is not updated in database table unless Session is processed.               
    2. No sy-subrc is returned.          
    3.Error log is created for error records.
    4.Updation in database table is always synchronous     
    <b>CALL TRANSACTION</b>
    1. Immediate updation in database table.
    2. Sy-subrc is returned.
    3. Errors need to be handled explicitly
    4. Updation in database table can be synchronous Or Asynchronous.
    <b>Error Handling in CALL TRANSACTION</b>
    When Session Method updates the records in database table, error records are stored in the log file. In Call transaction there is no such log file available and error record is lost unless handled. Usually you need to give report of all the error records i.e., records which are not inserted or updated in the database table. This can be done by the following method:
    <b>Steps for the error handling in CALL TRANSACTION</b>
    1.     Internal table for the data (structure similar to your local file)
    2.     BDCTAB like BDCDATA
    3.     Internal table BDCMSG like BDCMSGCOLL
    4.     Internal table similar to Ist internal table
         (Third and fourth steps are for error handling)
    5.     UPLOAD or WS_UPLOAD function to upload the data from the local file to itab. (Considering file is local file)
    6.     Loop at itab.
    Populate BDCTAB table.
    Call transaction <tr.code> using <Bdctab>
                              Mode <A/N/E>
                              Update <S/A>
                              Messages <BDCMSG>.
          Perform check.
          Refresh BDCTAB.
          Endloop.
    7     Form check.
    IF sy-subrc <> 0.  (Call transaction returns the sy-subrc if updating is not successful).
    Call function Format_message.
    (This function is called to store the message given by system and to display it along with record)
    Append itab2.
    Display the record and message.
    Regards,
    Santosh

  • What is the difference between these deep sleep methods?

    I have found two ways to put the MBP into "Deep Sleep"/Hibernation but I am not sure what the difference is. Could you help me?
    http://www.apple.com/downloads/dashboard/status/deepsleep.html
    http://www.apple.com/pro/tips/quicksleep.html
    Is the latter even Hibernation? Thanks for any help.

    Homework question?
    The answer is on this page (Step 5)
    http://java.sun.com/products/jsp/syntax/1.2/syntaxref1217.html#8865

  • Difference Betn EJB and Java Bean

    what is diference between EJB and Java Bean...???

    Is it really necessary to ask the same thing twice??
    MeTitus

  • Difference betn grid and RAC in 10g

    Hi all,
    I would like to know the differnce between terms grid and RAC in 10g.
    Thanks in advance.
    Chaitra

    http://tkyte.blogspot.com/2006/02/so-what-was-answer-part-iii.html

  • Topic about wait(),join(),sleep() and yield()

    Hi there,
    I'm headache with the implementation of wait()��join()�� sleep() yield(). Can anybody tell me:
    1. what's the difference between wait() and join(), I can't see it.
    2. As I know if thread A waits on thread B then A will release the lock. How about join, or slepp, or yield?
    3. Why use notify()? As I see if thread A waits on thread B, when B completed without calling notify(), the A will continue its job!!
    thanks thanks thanks

    1. Object.wait() will make a thread wait until Object.notify() is called on the object. Thread.join() will make the running thread to wait until the thread object finish to execute.
    2. .wait() does not wait on thread, it wait on objects. .sleep(long timeout) is about the same as .wait(long timeout), except that it need to be awaken with a .interrupt, not .notify. Also you cannot awaken more than one thread with a .interrupt, while a call to .notifyAll() will awaken all threads waiting on that object. .yield() suspend the current thread only to give a chance to others thread to execute and the initial thread will continue ot execute only a hort time after the .yield().
    3. See #1, #2 and think a bit.
    Regards

  • DoGet() and service() method differences in servlets

    can you give the differences between doGet() and service() methods in servlets. where to use doGet() and where to use service()
    thanks

    service() is called whenever the Servlet gets a HTTP request. Per default it calls the correct do<METHOD>() method.
    So doGet() is only called when you get a GET request via HTTP. For POST (for example) doPost() will be called instead.

  • Thread yield() and sleep()

    what is the different bettween yield() and sleep() method
    in thread
    i think sleep() method make the called thread to wait then
    make the way to enter any other
    but yield() also do same but dont allow lower priority threads
    allow only higher priority thread.
    is this correct?

    Thread.yield() is used to give other threads a chance to get a processor time slice, according to the thread dispatcher rules. If there are no other threads ready to run, the current thread will gain the processor again.
    Thread.sleep() will always release the processor for at least the amount of time specified, even if there are no other threads requesting it.

  • Difference betn 161-122

    what is Difference betn 161 and 122 movement type
    Nikhil

    Hi,
    I think the main difference is between return to vendor via 122 and 161 is that
    - in case of mvt 122 you post the GI with reference to the PO (directly to the material document(GR) and thus to the PO)
    - in case of mvt 161 you have to create a new PO / new PO item and you post the goods issue with reference to that.
    So, if you use mvt 122 the return goods movement will be linked to the original PO item. If you decide to use mvt 161 there will be no connection with the original PO item.
    If you booked IR for the PO item and you do not want to cancel it, you should use mvt 161 return process (in case of GR-Based IV).
    Please visit SAP online help.
    http://help.sap.com/erp2005_ehp_04/helpdata/EN/a5/63341243a211d189410000e829fbbd/frameset.htm
    http://help.sap.com/erp2005_ehp_04/helpdata/EN/a5/63351643a211d189410000e829fbbd/frameset.htm
    I think this is the most important when you compare the two methodes.
    I do not agree with Mr R.B. that 161 is "planned" and 122 is not "planned" - the same decision making process may be behind both scenario. Of course, there is difference between the processes from MRP ponit of view, maybe in this sense we can call mvt 161 as "planned" (even though it can be the result of an ad hoc decision...).
    Regards,
    Csaba

  • Wait() and notify() or Semaphores with single permits?

    Hi,
    What's the difference between using wait(), notify() and single permitted Semaphores? Does using the latter affect the performance in massively multi-threaded environments?

    I wrote a very simple program to simulate a Queue like structure, and a Producer with a Consumer which both are running in separate threads. I changed the Queue class to hold only one value (It's not a queue any more, but the name didn't change). Then I used a boolean value, wait() and notify() methods of the Object class to ensure that every put() by the producer is followed by a get() by the consumer. Here's the Queue class code:
    class Queue {
         private int num;
         private boolean valueSet = false;
         synchronized void put(int n) {
              while(valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("put() interrupted.");
              num = n;
              valueSet = true;
              notify();
              System.out.println("Put: "+n);
         synchronized int get() {
              while(!valueSet) {
                   try {
                        wait();
                   } catch(InterruptedException err) {
                        System.out.println("get() interrupted.");
              valueSet = false;
              notify();
              System.out.println("Got: "+num);
              return num;
    }Producer and Consumer classes simply repeat calling put() and get() methods respectively for a number of times. I also implemented all this by using Semaphores with single permits:
    import java.util.concurrent.*;
    class Queue {
         private int num;
         private final static Semaphore semCon = new Semaphore(0);
         private final static Semaphore semPro = new Semaphore(1);
         void put(int n) {
              try {
                   semPro.acquire();
              } catch(InterruptedException err) {
                   System.out.println("put() interrupted.");
              num = n;
              semCon.release();
              System.out.println("Put: "+n);
         int get() {
              try {
                   semCon.acquire();
              } catch(InterruptedException err) {
                   System.out.println("get() interrupted.");
              semPro.release();
              System.out.println("Got: "+num);
              return num;
    }Which one is better? Better in every aspect, such as performance, being maintainable, etc. I don't know whether it's a good idea to use Semaphores in these cases.
    Thanks for your reply.

  • A bug in wait and notify? -- help

    Now I am engaged in a simulation project. The threads are all controlled by the controller program, that is, they are often blocked and unblocked by using wait and notify methods. However, when I was debugging my program, there were always some errors occurring and halting the simulation. And I found that the cause was that the threads sometimes might halt after having executed the wait or notify methods!!
    Example,
    in thread 1, it would be blocked by a wait method like:
    synchronized(lock){
    lock.wait();
    System.out.println("Thread 1 go on.");
    In thread 2, it would unblock thread 1 with the notify method:
    synchrnoized(lock){
    System.out.println("Thread 2 would notify the threads blocked on lock.");
    lock.notifyAll();
    System.out.println("Thread 2 go on.");
    The simulation program controls the time to execute the thread 2. However, in debugging the program I often encountered the problem that thread 2 did notify thread 1 and thread would go on executing, but thread 2 would not go further. That is, the output is like:
    Thread 2 would notify the threads blocked on lock.
    Thread 1 go on.
    But the String, "Thread 2 go on." would not be printed out.
    It was so strange, and I repeated for tens of times, it always occurred here and there.
    Is it a bug of java?

    There seems to be nothing wrong with this to me:
    You should use better debugging messages. I couldn't read it the way you had it.
    public class BugThread extends Thread
        Object lock;
        Notifier notifier;
        public static void main(String[] arg)
            for(int i = 0; i < 5; i ++)
                Object lock = "lock " + i;
                Notifier noti = new Notifier(lock);
                BugThread bug = new BugThread(lock, noti);
                bug.start();
                noti.start();
        public BugThread(Object lock, Notifier notifier)
            this.lock = lock;
            this.notifier = notifier;
        public void run()
            int i = 0;
            while( i++ < 100)
                synchronized(lock)
                    System.out.println("Bug thread: "
                        + lock + " would block at Object: "
                        + lock);
                    try
                        lock.wait();
                    catch(InterruptedException ex)
                        ex.printStackTrace();
                    System.out.println("Bug thread: "
                        + lock + " unblocked at Object: "
                        + lock);
            notifier.stop();
    class Notifier extends Thread
        Object lock;
        public Notifier(Object lock)
            this.lock = lock;
        public void run()
            int i = 0;
            while(true)
                synchronized(lock)
                    System.out.println("Notifier: " + lock
                        + " would notify Bugthread blocking at object: "
                        + lock.toString() + ". time no." + i);
                    lock.notifyAll();
                    System.out.println("Notifier: " + lock
                        + " notified bugthread. time no." + i);
                System.out.println("Notifier: " + lock
                    + " go on working. time no." + i);
                i ++;
    }

  • How to fix wait and notify

    The program tries to find the first socket connection. Theirs a wait and the notify call in the inner class seams to have to effect. Attach is the code to try out
    import java.io.*;
    import java.util.*;
    import java.net.*;
    import java.nio.channels.*;
    * SocketSearch class to scan for an open socket from an array of sockets passed. <br>
    * Inner class DetectSocketConnection tries to open the socket and assign hostname
    * a value if successful. <br>
    * The SocketSearch thread class is waiting to find the hostname or active DetectSocketConnection
    * threads to be zero - i.e No hosts found
    public class SocketSearch extends Thread {
       private Object syncObject = new Object();
       private String hostname = null;
       private ThreadGroup threadGroup = new ThreadGroup("SOCKETS_CONNECT");
       private ArrayList sockets = null;
        * Inner class DetectSocketConnection to find an open socket. <br>
        * It will assign the hostname a value if successful
       private class DetectSocketConnection extends Thread {
          private SocketChannel sc = null;
          private String host = null;
          private int port = -1;
          public DetectSocketConnection(String host, int port) {
             super(threadGroup, host);
             this.host = host;
             this.port = port;
             System.out.println("DetectSocketConnection::syncObject = " + syncObject);     
          public void run() {
             System.out.println("Scanning " + host + " at port number " + port);
             synchronized(syncObject) {
                try {         
                   InetSocketAddress isa = new InetSocketAddress(InetAddress.getByName(host), port);
                       // Connect
                    sc = SocketChannel.open();
                sc.connect(isa);
                   System.out.println("Found hostname: " + host + "!!!!!!!!!!!!!!!!!!!");
                   hostname = host;
                catch (IOException e) {
                   System.err.println("DetectSocketConnection: " + e.toString());
                finally {
                // Make sure we close the channel (and hence the socket)
                   close();
                   System.out.println("DetectSocketSonnectio: notify()...");
                   syncObject.notify();
          public void close() {
             try {
                if (sc != null) sc.close();
             catch (IOException e) {
       public SocketSearch() {
          sockets = new ArrayList();
        * Add socket to the sockets ArrayList to prepare to start the Socket Search
        * @param host Socket hostname
        * @param port Socket port number
       public void addSocket(String host, int port) {
          DetectSocketConnection detectSocket = new DetectSocketConnection(host, port);
          sockets.add(detectSocket);
        * SocketSearch start method to fire up the sockets threads to search for
       public void start() {
          super.start();
          if (sockets != null) {
             DetectSocketConnection[] arrSockets = (DetectSocketConnection[]) sockets.toArray(new DetectSocketConnection[0]);
             for (int i = 0 ; i < arrSockets.length ; i++) {
                arrSockets.start();
    * Main code to do the socket search
    public void run() {
    try {
    boolean loop = (sockets.size() > 0);
    while (loop) {
    synchronized(syncObject) { 
    System.out.println("SocketSearch.wait() => syncObject = " + syncObject);
    syncObject.wait();
    System.out.println("SocketSearch.wait() => syncObject = " + syncObject + ", finished...");
    if (hostname != null) {     
    // use the hostname
    // you could interrupt the threads now - its your choice
    loop = false;
    else {
    System.out.println("Invalid hostname...");
    ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
    int numThreads = currentGroup.activeCount();
    Thread[] listOfThreads = new Thread[numThreads];
    currentGroup.enumerate(listOfThreads);
    int activeThreads = 0;
    for (int i = 0 ; i < numThreads ; i++) {
    if (listOfThreads[i] instanceof DetectSocketConnection) {
    activeThreads++;
    System.out.println("activeThreads: " + activeThreads);
    if (activeThreads == 0) {     
    // host name is NULL and active threads are finished
    throw new UnknownHostException("Host not found.");
    if (hostname != null) {
    System.out.println("Found hostname: " + hostname);
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    catch (UnknownHostException e) {
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    System.err.println(e.toString());
    catch (InterruptedException e) {
    // Do something here, use callback to maybe dispose ProgressDialog etc...
    System.err.println(e.toString());
    * Test to find a socket from an array of test socket hosts
    public static void main(String args[]) {
    String[] yahooPOP3PossibleSettings = new String[] {
    "yahoo.com",
    "mail.yahoo.com",
    "pop.yahoo.com",
    "pop.mail.yahoo.com",
    "pop3.yahoo.com"
    int PORT_NUMBER = 110;
    SocketSearch socketSearch = new SocketSearch();
    for (int i = 0 ; i < yahooPOP3PossibleSettings.length ; i++) {
    socketSearch.addSocket(yahooPOP3PossibleSettings[i], PORT_NUMBER);
    socketSearch.start();

    Forget it. The Inner class was doing a wait and so was the main thread.
    Not meant to put a wait in the main thread...

  • Difference Between doGet() and doPost

    Hi Everyone !!!
    I'm very new to servlets.I dont know what is the difference between doGet() and doPost() Method.
    Can anyone explain me .
    Can any give me details and differences between these two
    thanks in advance

    As you mention Why developer will use GET, if POST have all the advantages. Please look into, it may clear you doubts
    GET
    the GET type request is normally used for simple HTML page requests. The types of events that generate this type of request are clicking on a hyperlink, changing the address directly by typing in the address textbox on a browser or application that has HTML functionality, and submitting an HTML form where the method header is set to get as in method=get. Also, a GET request is triggered when selecting a favorite from the Favorites list and using JavaScript to change location.href. Usually the browser is configured to send a GET request even if no method is set explicitly by the HTML.
    The benefits of the GET method are
    1. It retrieves information such as a simple HTML page or the results of a database query.
    2. It supports query strings (name-value pairs appended to URL). Servers usually limit query strings to about      
         1024 characters.
    3. It allows bookmarks.
    POST
    This occurs when a browser or application submits an HTML form with the method attribute set to post as in method=post.
    The benefits of the POST method are
    1. It sends information to the server such as form fields, large text bodies, and key-value pairs.
    2. It hides form data because it isn't passed as a query string, but in the message body.
    3. It sends unlimited length data as part of its HTTP request body.
    4. It disallows bookmarks.
    Conclusion, always prefer to use GET, except mentioned in the following reason:
    1. If data is sensitive
    2. It is greater than 1024 characters
    3. If your application don't need bookmarks
    As because GET is more faster than POST.
    Both are used to send the request to the server, if you analyze than you may make the differnces like
    In the case of GET means send the request to get the simple HTML page from server whereas, in the case of POST means send the request to post the data to server.
    By Ausaf Ahmad
    Message was edited by:
    Genius_Brainware

Maybe you are looking for

  • "There was a problem connecting to the server.   URLs with the type "file:" are not supported.  Why?  What can be done to eliminate it?

    After upgrading to Mountain Lion, I repeatedly get this message:  "There was a problem connecting to the server.   URLs with the type "file:" are not supported.  Why?  What can be done to eliminate it?

  • I keep getting error msg "Oops! Firefox could not find..." a lot!

    On websites that I visit often, I have started to receive "Oops! Firefox could not find xlforum.net", etc. This is happening a lot. I've already done a virus/malware scan and the problem still exists. Any idea what's going on? == URL of affected site

  • IMAC 24" cursor moves, can't click

    My iMAC 24" (Late 2007) just started randonly freezing up. I can move the bluetooth mouse pointer, but can not click on anything.  Keyboard doesn't work either.  Only way out is to hold power button down and shut off/restart. I was able to locate the

  • ODI installation out of Oracle home

    Hi, I have to install Oracle Data Integrator on a development server where EPM 11.1.2 is already installed. I encounter the following error after setting the install folder (I leave it to default: D:\Oracle\Middleware\EPMSystem11R1): OUI-10044: The s

  • Urgent help in AS3

    Hi I'm new in new in this Forum and to As3. I would really appreciate it if you guys could help me with nuisance that have been bothering for a while now. I'm trying to make a simple registration page - where the user when typing the right password w