java tutorial - How to create thread in Java - java programming - learn java - java basics - java for beginners



  • There are two ways using to create a thread,
    • By extending Thread class
    • By implementing Runnable interface.

Thread class:

  • Thread class provide constructors and methods to create and perform operations on a thread.
  • Thread class extends Object class and implements Runnable interface.

Constructors of Thread class:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)

Methods of Thread class:

Methods Description
public void run() Used to perform action for a thread.
public void start() Starts the execution of the thread. Then the Java Virtual Machine (JVM) calls the run() method on the thread.
public void sleep(long miliseconds) It causes the presently executing thread to sleep for the specified number of milliseconds.
public void join() Waits for a thread to die.
public void join(long miliseconds) waits for a thread to die for the specified miliseconds.
public int getPriority() Returns the priority of the thread.
public int setPriority(int priority) Changes the priority of the thread.
public String getName() Returns the name of the thread.
public void setName(String name) Changes the name of the thread.
public Thread currentThread() Returns the reference of currently executing thread.
public int getId() Returns the id of the thread.
public Thread.State getState() Returns the state of the thread.
public boolean isAlive() Tests if the thread is alive.
public void yield() Causes the currently executing thread object to temporarily pause and allow other threads to execute.
public void suspend() Used to suspend the thread(depricated).
public void resume() Used to resume the suspended thread(depricated).
public void stop() Used to stop the thread(depricated).
public boolean isDaemon() Tests if the thread is a daemon thread.
public void setDaemon(boolean b) Marks the thread as daemon or user thread.
public void interrupt() Interrupts the thread.
public boolean isInterrupted() Tests if the thread has been interrupted.
public static boolean interrupted() Tests if the current thread has been interrupted.

Related Searches to How to create thread in Java