Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 5 of 5

Thread: Questions About Threads

  1. #1
    Junior Member
    Join Date
    Jul 2009
    Location
    SomeWhere in the world
    Posts
    27
    Thanks
    1
    Thanked 11 Times in 6 Posts

    Question Questions About Threads

    I need to know what is the difference between sleep() and wait() methods in Thread Class.
    my second question:
    How to make two threads shared a block of memory.
    Thanks a lot.


  2. #2
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Questions About Threads

    First of all, when you call Thread.sleep(ms, ns) which btw is a static method, you sleep the currently running thread for the time specified. When using wait() you tell a thread to wait on a certain object. So for instance if you were to synchronize on an object and then call wait, you would tell the thread that it should just hang on and do nothing until someone calls notify on the object you are waiting for. Once you call notify any waiting thread that gets awaken will start right from were it started waiting.

    An example of this could be if you have an event system with a shared pool of events to take care of. Lets say you have 3 threads all polling the event queue and popping whatever is on the stack at the moment. What you could then do is check if the stack is empty and if it is you just tell the thread to wait(), after a while all 3 threads will be waiting and not doing anything and whenever there is an event coming in you simply call notify on the queue object which will awake 1 or more threads waiting for the object and they will continue working on it.

    I hope that makes any sense.


    Over to having several threads share an object or in your case you might be thinking of just a stack of events or a list or whatever. I made a small example to show most of this stuff off. Enjoy!

    import java.util.Queue;
    import java.util.concurrent.LinkedBlockingQueue;
     
    public class Testing
    {
    	public static void main(String... arguments)
    	{
    		// Create our selfs a little queue
    		final Queue<String> eventQueue = new LinkedBlockingQueue<String>();
     
    		// Start worker 1
    		final Thread thread1 = new Thread(new MyWorkerThread(eventQueue));
    		thread1.start();
     
    		// Start worker 2
    		final Thread thread2 = new Thread(new MyWorkerThread(eventQueue));
    		thread2.start();
     
    		// Start employer
    		final Thread employer = new Thread(new MyEmployerThread(eventQueue));
    		employer.start();
    	}
     
    	private static class MyEmployerThread implements Runnable
    	{
    		private Queue<String> eventQueue;
     
    		private int counter = 0;
     
    		public MyEmployerThread(final Queue<String> eventQueue)
    		{
    			this.eventQueue = eventQueue;
    		}
     
    		@Override
    		public void run()
    		{
    			while (true)
    			{
    				try
    				{
    					synchronized (this.eventQueue)
    					{
    						++this.counter;
    						this.eventQueue.add("event " + this.counter);
    						this.eventQueue.notify();
    					}
     
    					System.out.println("Added event to queue");
    					Thread.sleep(150);
    				}
    				catch (InterruptedException e)
    				{
    					e.printStackTrace();
    				}
    			}
    		}
    	}
     
    	private static class MyWorkerThread implements Runnable
    	{
    		private Queue<String> eventQueue;
     
    		public MyWorkerThread(final Queue<String> eventQueue)
    		{
    			this.eventQueue = eventQueue;
    		}
     
    		@Override
    		public void run()
    		{
    			while (true)
    			{
    				synchronized (this.eventQueue)
    				{
    					if (this.eventQueue.isEmpty())
    					{
    						try
    						{
    							this.eventQueue.wait();
    						}
    						catch (InterruptedException e)
    						{
    							e.printStackTrace();
    						}
    					}
    				}
     
    				// Carry on executing from this point once we are notified
    				final String eventString = this.eventQueue.poll();
     
    				if (eventString != null)
    				{
    					System.out.println("[" + Thread.currentThread().getName() + "] executing " + eventString + " leaving the queue at size [" + this.eventQueue.size() + "]");
    				}
     
    				// Lets sleep a little just in case the queue
    				// is endless we might want to give the rest
    				// of the system some CPU time
    				try
    				{
    					Thread.sleep(100);
    				}
    				catch (InterruptedException e)
    				{
    					e.printStackTrace();
    				}
    			}
    		}
    	}
    }

    Happy programming!

    // Json

  3. #3
    Junior Member
    Join Date
    Jul 2009
    Location
    SomeWhere in the world
    Posts
    27
    Thanks
    1
    Thanked 11 Times in 6 Posts

    Default Re: Questions About Threads

    Thanks a lot for your effort
    Perfect sample....Good Person

  4. #4
    Junior Member
    Join Date
    Mar 2010
    Location
    Home-Ujjain /Job-Mumbai
    Posts
    24
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Questions About Threads

    if you r using sleep() means you have to stop the thread for a particular time period given in neno seconds and the thread automaticaly resumes after that time but wait() is used to stop a thread for a particular condition you have to resume the thread explicitly.

  5. #5
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: Questions About Threads

    Its important to note that sleep is actually a method on the Thread class while wait is a method on the Object class. You tell a thread to wait for an object's notify to be called while sleep is just a way of telling the thread to wait for no particular reason.

    // Json

Similar Threads

  1. 50 SCJP Mock Exam Questions with Answers
    By JavaPF in forum The Cafe
    Replies: 3
    Last Post: July 6th, 2010, 11:10 AM
  2. [SOLVED] Fixing of bug for a small program
    By Koren3 in forum Threads
    Replies: 3
    Last Post: April 21st, 2009, 06:28 AM