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

(2pts + 2pts) Consider the sum program we studied in class consisting of two thr

ID: 664097 • Letter: #

Question

(2pts + 2pts) Consider the sum program we studied in class consisting of two threads. Shown below.

Identify a sequence where all statements are executed and the final value of sum is 3. (You can write sequence such as 1-2, a-f,3-10,g-j, i.e., no need to repeat the code of each thread.

Insert appropriate wait and signal statements so that the run you chose is executed. The code you enter must guarantee that all statements are executed, i.e., no thread waits on a semaphore forever. Also, you can only add wait and signal statements only. No statements of the form jump, if-then-else etc. Specify the initial values of each semaphores you use.

Explanation / Answer

class RunnableDemo implements Runnable { private Thread t; private String threadName; RunnableDemo( String name){ threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // Let the thread sleep for a while. Thread.sleep(50); } } catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } public void start () { System.out.println("Starting " + threadName ); if (t == null) { t = new Thread (this, threadName); t.start (); } } } public class TestThread { public static void main(String args[]) { RunnableDemo R1 = new RunnableDemo( "Thread-1"); R1.start(); RunnableDemo R2 = new RunnableDemo( "Thread-2"); R2.start(); } }