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

8. [10] Consider the following code: public void run() { System.out.print(\"GREE

ID: 662985 • Letter: 8

Question

8. [10] Consider the following code:

public void run() {

System.out.print("GREEN");

System.out.print("RED"); }

public void execute() {

ExecutorService executor = Executors.newCachedThreadPool();

executor.execute(this); executor.execute(this);

executor.shutdown(); }

a. (5) Is it possible for the above code to print anything other than "GREEN RED GREEN RED"? Why?

b. (5) How would the behavior of the above code change if the run() method was synchronized (i.e., defined using the synchronized keyword)? Why?

Explanation / Answer

a.

Yes , it is possible for the function to print other type of combination like:

i. GREEN GREEN RED RED

because these are threads. So after printing "GREEN" from first child, that process can go into sleep while the scond process prints GREEN and the both prints RED. As these process are not synchronized and are independent threads

b.

Then it would always print: GREEN RED GREEN RED because the second thread would be created only after first thread completes which prints "GREEN RED" and then the second process starts and prints "GREEN RED" . Hence only one output will be available

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote