Part A:
i. Create a java class that implements the Runnable interface and prints numbers from 1 to 100.
ii. Create a static main function (within the same or a separate class) in which you instantiate a new instance of the above class and call the run() method. Print “THE END” after the call to the run() method.
Note: this version do not use threading.
Part B:
iii. Revise the above main function such that instead of a
direct call to the run() method, create a thread and execute in a
separate thread. See the example in the above link.
Question: Do you see any changes in the output result?
Answer 1:
public class ThreadExample implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 100;
i++)
System.out.println(i);
}
public static void main(String[] args) {
ThreadExample th = new
ThreadExample();
th.run();
System.out.println("THE
END");
}
}
Answer 2:
public class ThreadExample implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 100;
i++)
System.out.println(i);
}
public static void main(String[] args) {
ThreadExample th = new
ThreadExample();
Thread t = new Thread(th);
t.start();
System.out.println("THE
END");
}
}
In the first program we are not using the threading so the THE END is printed in the end because after executing the run() method it will execute remaining statements in the main()
In the second program we are using threading and main() ad threads will execute both parellely
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me
Get Answers For Free
Most questions answered within 1 hours.