JAVA use the concepts in concurrent programming to write a basic multi-threaded
ID: 3803737 • Letter: J
Question
JAVA
use the concepts in concurrent programming to write a basic multi-threaded program. You will be creating a program that simulates the sound of soldiers marching: “Left, Left, Left, Right, Left”.
You will need one class to print “Left” and one to print “Right”, as well as a class to drive the program.
LeftThread.java
RightThread.java
MilitaryMarching.java
Is there a problem with this implementation? Why does it sometimes give the wrong output?
This implementation will likely give you the right result the majority of the time, however sometimes LeftThread and RightThread will be running on different processor cores. In this case, yielding will not work because there is no other process on the same processor to yield to.
What would we need to do to fix this problem?
To fix this issue, we will need to poll our threads. This means, we would need variables in each of our threads corresponding to the other thread to keep track of whether it is done or not. Our LeftThread would need a boolean, done, and a reference to our RightThread, right. Or RightThread would also need a boolean, done, and a reference to our LeftThread, left. We can keep track of whether the other thread is done before progressing into our print statements. Once we print, we can set our current thread to done so that the other thread knows to take over.
Explanation / Answer
public class NewThread
{
public static void main(String[] args){
Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread th, Throwable ex) {
System.out.println("Uncaught exception: " + ex);
}
};
Thread t = new Thread() {
public void run() {
System.out.println("Sleeping ...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interrupted.");
}
System.out.println("Throwing exception ...");
throw new RuntimeException();
}
};
t.setUncaughtExceptionHandler(h);
t.start();
}
}
Well, you can use this to catch the exception thrown by thread. And I didn't understand in which basis are iterating for loop for 10 times. If I get to know this I can explain further.Thank you.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.