ExamVeda
Login
Home
This question belongs to Java Program Threads
Threads
?

What will be the output of the following Java program?
class newthread extends Thread
{
Thread t;
newthread()
    {
  t1 = new Thread(this,"Thread_1");
  t2 = new Thread(this,"Thread_2");
  t1.start();
  t2.start();
}
public void run()
    {
  t2.setPriority(Thread.MAX_PRIORITY);	
  System.out.print(t1.equals(t2));
    }    
}
class multithreaded_programing
{
    public static void main(String args[])
    {
        new newthread();        
    }
}

Answer & Solution
Correct Answer: Option D
In the given program, the class newthread extends Thread, and within its constructor, it creates two thread objects: t1 and t2.

Both threads are started with t1.start() and t2.start(), and they both execute the same run() method of the class instance because this is passed as the target.

Inside the run() method, the priority of t2 is set to Thread.MAX_PRIORITY. However, this has no effect on the logic or output because thread priority only suggests execution preference to the scheduler.

The key line is System.out.print(t1.equals(t2)); which checks if t1 and t2 are equal.

Since t1 and t2 are two separate thread instances, the equals() method returns false.

Because both threads run the same run() method, the output false is printed twice — once by each thread.

Hence, the output is falsefalse.
Examveda
Question posted by Examveda
Community

Join the Discussion

1 Comment
Ganesh Commn
Ganesh Commn 1 year ago
Variable Naming Mismatch:

The class declares Thread t but tries to use t1 and t2 which aren't declared

This will cause a compilation error