JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Java Threads Examples

  • Threading is a facility to allow multiple tasks to run concurrently within a single process. Threads are independent, concurrent execution through a program, and each thread has its own stack.
  • In Java threads can be implemented in two ways. One is by 'Extending Thread Class' and the other way is by 'Implementing Runnable Interface'
  • Extending Thread Class is required to 'override run()' method. The run method contains the actual logic to be executed by thread.
  • Creation of thread object never starts execution, we need to call 'start()' method to run a thread. Examples gives you more details. Other methods supported by Threads are given below.
  • join(): It makes to wait for this thread to die. You can wait for a thread to finish by calling its join() method.
  • sleep(): It makes current executing thread to sleep for a specified interval of time. Time is in milli seconds.
  • yield(): It makes current executing thread object to pause temporarily and gives control to other thread to execute.
  • notify(): This method is inherited from Object class. This method wakes up a single thread that is waiting on this object's monitor to acquire lock.
  • notifyAll(): This method is inherited from Object class. This method wakes up all threads that are waiting on this object's monitor to acquire lock.
  • wait(): This method is inherited from Object class. This method makes current thread to wait until another thread invokes the notify() or the notifyAll() for this object.

Java Threads Sample Code Examples

Knowledge Centre
wait Vs sleep methods
sleep(): It is a static method on Thread class. It makes the current thread into the "Not Runnable" state for specified amount of time. During this time, the thread keeps the lock (monitors) it has acquired.

wait(): It is a method on Object class. It makes the current thread into the "Not Runnable" state. Wait is called on a object, not a thread. Before calling wait() method, the object should be synchronized, means the object should be inside synchronized block. The call to wait() releases the acquired lock.
Famous Quotations
We know what we are, but know not what we may be.
-- William Shakespeare

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.