Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

1.) Write an Application that extends the Thread class, call it MyThread.java. H

ID: 3864632 • Letter: 1

Question

1.) Write an Application that extends the Thread class, call it MyThread.java. Have your new class accept an integer(i.e. 200) when it is instantiated. (MyThread mt = new MyThread(200); ) This integer number will be the number of times that this class loops and prints a message. The message should read “Thread Running…200”. The 200 would be whatever number is passed into the constructor. If the number was 300, then the output should read “ Thread Running ….. 300”. Use a main method to test this class. In the main start 2 Threads, one Thread with 250 and one Thread with 300. What happens? You do not need to use the sleep() method for this

2.) Modify 1.) from above. Change this class to use the Runnable Interface instead of the Thread class. Any difference how the code runs?

3.) Lastly, have the main method start 4 different threads, all with different loop counts.

Explanation / Answer

Thread Application:-

* To develop multiple custom threads to execute same logic with the inputs given by another programmer we must develop either parameterized method or parameterized constructor to receive input values. why Because run() method is a non-parameterized method.
* If we define parameterized method we may forget to call this method before starting the thread. so it is recommended to define parameterized constructor. why Because If you forget to call parameterized constructor compiler will throw an error because our program does not contain no-parameterized constructor.

Working Code:-

class MyThread extends Thread
{
private int x;
// Constructor Approach
MyThread(int x)
{
this.x = x;
}
public void run( )
{
// From this if condition, we are throwing Exception to inform to user programmer that object is not initialized.
if(x<=0)
{
throw new IllegalArgumentException("Object should be initialized with the Positive No");
}

for(int i=1;i<=x;i++)
{
System.out.println("Thread Running…"+i);
}
}
}

class Demo
{
public static void main(String[] args)
{
MyThread mt = new MyThread(250);
mt.start();
MyThread mt1 = new MyThread(300);
mt1.start();
MyThread mt2 = new MyThread(350);
mt2.start();
MyThread mt3 = new MyThread(400);
mt3.start();

}
}

Conclusion:-

run() method logic is executed four times concurrently from Thread-0,Thread-1,Thread-2,Thread-3.

Output:-

In Thread-0 run() method executes 250 iterations.
In Thread-1 run() method executes 300 iterations.
In Thread-2 run() method executes 350 iterations.
In Thread-3 run() method executes 400 iterations.