0% found this document useful (0 votes)
19 views10 pages

Java Thread Class Methods Explained

The Java Thread Methods document describes 12 key methods of the Thread class in Java: 1. start() - Starts the execution of the thread and calls its run() method. 2. run() - The main method that is executed when a thread runs. 3. sleep() - Blocks the currently running thread for a specified time period. 4. currentThread() - Returns a reference to the currently running thread. 5. join() - Blocks the calling thread until another thread finishes execution. 6. getPriority() - Returns the priority of the thread. 7. setPriority() - Changes the priority of the thread. 8. getName() - Returns the name of the thread

Uploaded by

Divya G
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views10 pages

Java Thread Class Methods Explained

The Java Thread Methods document describes 12 key methods of the Thread class in Java: 1. start() - Starts the execution of the thread and calls its run() method. 2. run() - The main method that is executed when a thread runs. 3. sleep() - Blocks the currently running thread for a specified time period. 4. currentThread() - Returns a reference to the currently running thread. 5. join() - Blocks the calling thread until another thread finishes execution. 6. getPriority() - Returns the priority of the thread. 7. setPriority() - Changes the priority of the thread. 8. getName() - Returns the name of the thread

Uploaded by

Divya G
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Thread Methods

These are the methods that are available in the Thread class:

1. public void start()

It starts the execution of the thread and then calls the run() on this Thread object.

Example:

1
2 {
    public void run()
3     {
4         [Link]("Thread is running...");
5     }
6     public static void main(String args[])
7     {
        StartExp1 thread1=new StartExp1();
8         [Link]();
9     }
10 }
11
Output:

Thread is running…

2. public void run()

This thread is used to do an action for a thread. The run() method is instantiated if the thread
was constructed using a separate Runnable object.

Example:

1 public class RunExp1 implements Runnable


{
2
    public void run()
3     {
4         [Link]("Thread is running...");
5     }
6     public static void main(String args[])
    {
7         RunExp1 r1=new RunExp1();
8         Thread thread1 =new Thread(r1);
9         [Link]();
10     }
}
11
12
13
Output:

Thread is running…

3. public static void sleep()

This blocks the currently running thread for the specified amount of time.

Example:

1
2
3 public class SleepExp1 extends Thread
{
4     public void run()
5     {
6         for(int i=1;i<5;i++)
7         {
            try
8             {
9                 [Link](500);
10             }catch(InterruptedException e){[Link](e);}
11             [Link](i);
12         }
    }
13     public static void main(String args[])
14     {
15         SleepExp1 thread1=new SleepExp1();
16         SleepExp1 thread2=new SleepExp1();
        [Link]();
17
        [Link]();
18     }
19 }
20
21
Output:

3
3

4. public static Thread currentThread()

It returns a reference to the currently running thread.

Example:

1
2 public class CurrentThreadExp extends Thread
3 {
4     public void run()
    {
5         [Link]([Link]().getName());
6     }
7     public static void main(String args[])
8     {
        CurrentThreadExp thread1=new CurrentThreadExp();
9
        CurrentThreadExp thread2=new CurrentThreadExp();
10         [Link]();
11         [Link]();
12     }
13 }
14
Output:

Thread-0

Thread-1

5. public void join()

It causes the current thread to block until the second thread terminates or the specified
amount of milliseconds passes.

Example:

1 public class JoinExample1 extends Thread


{
2
    public void run()
3     {
4         for(int i=1; i<=4; i++)
5         {
6
7
8             try
9             {
10                 [Link](500);
            }catch(Exception e){[Link](e);}
11
            [Link](i);
12         }
13     }
14     public static void main(String args[])
15     {
        JoinExample1 thread1 = new JoinExample1();
16         JoinExample1 thread2 = new JoinExample1();
17         JoinExample1 thread3 = new JoinExample1();
18         [Link]();
19        try
20         {
        [Link]();
21         }catch(Exception e){[Link](e);}
22         [Link]();
23         [Link]();
24     }
}
25
26
27
Output:

4
4

6. public final int getPriority()

It is used to check the priority of the thread. When a thread is created, some priority is
assigned to it. This priority is assigned either by the JVM or by the programmer explicitly
while creating the thread.

Example:

1
2 public class JavaGetPriorityExp extends Thread
3 {
4     public void run()
5     {
        [Link]("running thread name is:"+[Link]().getName()
6     }
7     public static void main(String args[])
8     {
9         JavaGetPriorityExp t1 = new JavaGetPriorityExp();
        JavaGetPriorityExp t2 = new JavaGetPriorityExp();
10
        [Link]("t1 thread priority : " + [Link]());
11         [Link]("t2 thread priority : " + [Link]());
12         [Link]();
13         [Link]();
14     }
}
15
16
Output:

t1 thread priority : 5

t2 thread priority : 5

running thread name is:Thread-0

running thread name is:Thread-1

7. public final void setPriority()

This method is used to change the priority of the thread. The priority of every thread is
represented by the integer number from 1 to 10. The default priority of a thread is 5.

Example:

1 public class JavaSetPriorityExp1 extends Thread


2
3 {
4     public void run()
    {
5         [Link]("Priority of thread is: "+[Link]().getPriori
6     }
7     public static void main(String args[])
8     {
        JavaSetPriorityExp1 t1=new JavaSetPriorityExp1();
9
        [Link](Thread.MAX_PRIORITY);
10         [Link]();
11     }
12 }
13
Output:

Priority of thread is: 10

8. public final String getName()

This method of thread class is used to return the name of the thread. We cannot override this
method in our program, as this method is final.

Example:

1
2 public class GetNameExample extends Thread
3 {
4     public void run()
5     {
        [Link]("Thread is running...");
6     }
7     public static void main(String args[])
8     {
9         // creating two threads
10         GetNameExample thread1=new GetNameExample();
        GetNameExample thread2=new GetNameExample();
11         [Link]("Name of thread1: "+ [Link]());
12         [Link]("Name of thread2: "+[Link]());
13         [Link]();
14         [Link]();
    }
15
}
16
17
Output:

Name of thread1: Thread-0

Name of thread2: Thread-1


Thread is running…

Thread is running…

9. public final void setName()

This method changes the name of the thread.

Example:

1
2 public class SetNameExample extends Thread
3 {
4     public void run()
5     {
6         [Link]("running...");
    }
7     public static void main(String args[])
8     {
9         SetNameExample thread1=new SetNameExample();
10         SetNameExample thread2=new SetNameExample();
        [Link]();
11
        [Link]();
12         [Link]("Kadamb Sachdeva");
13         [Link]("Great learning");
14         [Link]("After changing name of thread1: "+[Link]());
15         [Link]("After changing name of thread2: "+[Link]());
    }
16 }
17
18
Output:

After changing name of thread1: Kadamb Sachdeva

After changing name of thread2: Great Learning

running…

running…

10. public long getId()

It returns the identifier of the thread. The thread ID is a number generated when the thread
was created. This ID cannot be changed during its lifetime. But when the thread is
terminated, the ID can be reused.
Example:

1
2 public class GetIdExample extends Thread
3 {
4     public void run()
    {
5         [Link]("running...");
6     }
7     public static void main(String args[])
8     {
        GetIdExample thread1=new GetIdExample();
9
        [Link]("Name of thread1: "+[Link]());
10         [Link]("Id of thread1: "+[Link]());
11         [Link]();
12     }
13 }
14
Output:

Name of thread1: Thread-0

Id of thread1: 21

running…

11. public final boolean isAlive()

This method checks if the thread is alive. A thread is in the alive state if the start() method of
thread class has been called and the thread has not yet died.

Example:

1 public class JavaIsAliveExp extends Thread


{
2
    public void run()
3     {
4         try
5         {
6             [Link](300);
            [Link]("is run() method isAlive "+[Link]().isAl
7         }
8         catch (InterruptedException ie) {
9         }
10     }
11     public static void main(String[] args)
    {
12         JavaIsAliveExp thread1 = new JavaIsAliveExp();
13         [Link]("before starting thread isAlive: "+[Link]());
14         [Link]();
15         [Link]("after starting thread isAlive: "+[Link]());
16
17
    }
18 }
19
20
Output:

before starting thread isAlive: false

after starting thread isAlive: true

is run() method isAlive true

12. public static void yield()

This method pauses the execution of the current thread to execute other threads temporarily.

Example:

1
2
public class JavaYieldExp extends Thread
3 {
4     public void run()
5     {
6         for (int i=0; i<3 ; i++)
7             [Link]([Link]().getName() + " in control");
    }
8     public static void main(String[]args)
9     {
10         JavaYieldExp thread1 = new JavaYieldExp();
11         JavaYieldExp thread2 = new JavaYieldExp();
        [Link]();
12
        [Link]();
13         for (int i=0; i<3; i++)
14         {
15             [Link]();
16             [Link]([Link]().getName() + " in control");
        }
17     }
18 }
19
20
Output:

main in control

main in control
main in control

Thread-0 in control

Thread-0 in control

Thread-0 in control

Thread-1 in control

Thread-1 in control

Thread-1 in control

Common questions

Powered by AI

Thread identity in Java, defined by its unique ID and state (active, sleeping, waiting, or terminated), enables fine-grained control over thread execution, thereby supporting safe data access and manipulation. By checking thread states and identities using methods like 'isAlive()' and controlling execution order with 'join()' and priorities, a program can synchronize access to shared resources, prevent concurrent data modifications, reduce data races, and manage resource contention, ensuring consistency and stability in multithreaded applications .

The 'yield()' method allows a thread to voluntarily pause its execution, causing the thread scheduler to potentially switch execution to another thread of equal priority. It can improve performance and fairness by reducing thread dominance in CPU time allocation and granting equal access to processor resources among competing threads. However, its effectiveness depends on JVM implementation and operating system scheduling, which may not always result in the anticipated thread-switching behavior .

In Java, each thread is assigned a default name, such as 'Thread-0', based on its creation sequence. 'getName()' retrieves a thread's current name, while 'setName()' allows renaming, facilitating better identification of threads in logs or debugging outputs. Naming threads improves manageability, especially in systems with multiple threads, as distinct names can simplify understanding and tracking thread roles and functionalities within a program .

Thread priorities in Java, ranging from 1 (lowest) to 10 (highest), influence the order in which threads are scheduled for execution. The 'getPriority()' method retrieves a thread's priority, while 'setPriority()' modifies it. Although these priorities suggest how threads should be scheduled, they do not guarantee execution order due to JVM differences in thread handling. Modifying priorities can optimize task execution in time-sensitive applications .

The 'isAlive()' method checks whether a thread has been started and not yet terminated. It assists in managing thread synchronization by allowing developers to ascertain a thread's execution status. This can be vital for synchronization, as operations dependent on thread completion can utilize 'isAlive()' to verify that a thread has concluded, preventing premature access to shared resources and reducing synchronization errors .

The 'start()' method in Java is used to initiate the execution of a new thread by calling the 'run()' method internally on that Thread object. By contrast, if 'run()' is called directly, it does not initiate a separate thread but merely executes the method's body within the calling thread, behaving like a normal method call. The 'start()' method enables new concurrent execution on a separate call stack .

The 'getId()' method fetches a unique identifier for a thread, which remains constant throughout the thread's life. This ID is crucial in debugging multithreaded applications as it helps track and differentiate each thread's execution, troubleshoot concurrency issues, and identify bottlenecks or deadlocks. Since IDs can be reused after a thread concludes, distinguishing threads becomes imperative in complex systems .

The 'join()' method in Java makes the current thread wait until another thread completes its execution, thereby ensuring that the subsequent code executes only after the thread has finished. It is particularly useful in scenarios where a dependent action requires the completion of previously initiated threads to maintain thread synchronization and proper task sequencing, such as in transactional operations where a step cannot proceed until another completes .

The 'sleep()' method in Java temporarily ceases the current thread's execution for a specified time, enabling other threads to execute. It affects thread scheduling by moving the sleeping thread to a wait state, allowing the CPU to allocate time to other threads. This can help manage resource usage and optimize thread scheduling for better concurrency management .

Default thread priorities in Java might lead to issues such as imbalance in CPU allocation where lower-priority threads starve if high-priority threads monopolize processor time. To address these challenges, developers can adjust priorities using 'setPriority()' to ensure critical tasks receive timely resources while maintaining fairness. Additionally, implementing scheduling policies and strategic yield/collaboration methods might balance CPU time allocation among threads, based on the application's performance and responsiveness needs .

You might also like