Question

JAVA use the concepts in concurrent programming to write a basic multi-threaded program. You will be...

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

public class LeftThread extends Thread {
    public void run() {
       for(int i = 0; i < 10; i++) {
          //TODO: Print "Left"
          //TODO: Print "Left"
          //TODO: Yield and allow right thread an opportunity to take over
          //TODO: Print "Left"
       }
}

RightThread.java

public class RightThread /*TODO: What should this extend?*/ {
    public void run() {
       //TODO: Use LeftThread as template to print "Right" and yield for left thread
       //Make sure this process repeats 10 times like in the LeftThread
    }
}

MilitaryMarching.java

public class MilitaryMarching {
    public static void main(String[] args) {
        //TODO: Create left and right thread objects
        //TODO: Start left and right thread objects
        try {
        //TODO: Join left and right thread objects
        } catch(InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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.

Homework Answers

Answer #1

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.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Java Program: You will be inserting values into a generic tree, then printing the values inorder,...
Java Program: You will be inserting values into a generic tree, then printing the values inorder, as well as printing the minimum and maximum values in the tree. Given main(), write the methods in the 'BSTree' class specified by the // TODO: sections. There are 5 TODOs in all to complete. Ex: If the input is like ferment bought tasty can making apples super improving juice wine -1 the output should be: Enter the words on separate lines to insert...
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class....
Complete the redblacktree in Java. Add a public boolean isBlack field to the Node inner class. Make every Node object have a false isBlack field, all new node is red by default. In the end of the insert method, set the root node of your red black tree to be black. Implement the rotate() and recolor() functions, and create tests for them in a separate class. import java.util.LinkedList; public class BinarySearchTree<T extends Comparable<T>> { protected static class Node<T> { public...
IN JAVA!! You may be working with a programming language that has arrays, but not nodes....
IN JAVA!! You may be working with a programming language that has arrays, but not nodes. In this case you will need to save your BST in a two dimensional array. In this lab you will write a program to create a BST modelled as a two-dimensional array. The output from your program will be a two-dimensional array.   THEN: practice creating another array-based BST using integers of your choice. Once you have figured out your algorithm you will be able...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. v import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use...
Take the Java program Pretty.java and convert it to the equivalent C program. You can use the file in.txt as sample input for your program. import java.io.*; import java.util.*; public class Pretty { public static final int LINE_SIZE = 50; public static void main(String[] parms) { String inputLine; int position = 1; Scanner fileIn = new Scanner(System.in); while (fileIn.hasNextLine()) { inputLine = fileIn.nextLine(); if (inputLine.equals("")) { if (position > 1) { System.out.println(); } System.out.println(); position = 1; } else {...
In this Java programming assignment, you will practice using selection statements to determine whether a given...
In this Java programming assignment, you will practice using selection statements to determine whether a given year in the past or future qualifies as a “Leap Year”. I. Design a class called LeapYear in a file called LeapYear.java. This class will hold the main method and the class method that we will write in this assignment. II. Write an empty public static void main(String[] args) method. This method should appear inside the curly braces of the LeapYear class. III. Write...
C++ Programming   You are to develop a program to read Baseball player statistics from an input...
C++ Programming   You are to develop a program to read Baseball player statistics from an input file. Each player should bestored in a Player object. Therefore, you need to define the Player class. Each player will have a firstname, last name, a position (strings) and a batting average (floating point number). Your class needs to provide all the methods needed to read, write, initialize the object. Your data needs to be stored in an array of player objects. The maximum...
In this lab, you will write a program that creates a binary search tree based on...
In this lab, you will write a program that creates a binary search tree based on user input. Then, the user will indicate what order to print the values in. **Please write in C code** Start with the bst.h and bst.c base code provided to you. You will need to modify the source and header file to complete this lab. bst.h: #ifndef BST_H #define BST_H typedef struct BSTNode { int value; struct BSTNode* left; struct BSTNode* right; } BSTNode; BSTNode*...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class...
ALL CODE MUST BE IN C++ Before you begin, you must write yourself a LinkedList class and a Node class (please name your classes exactly ​as I did here). Please follow the below specifications for the two classes. Node.cpp ● This must be a generic class. ● Should contain a generic member variable that holds the nodes value. ● Should contain a next and prev Node* as denoted here. ● All member variables should be private. ● Use public and...
/* This program should check if the given integer number is prime. Reminder, an integer number...
/* This program should check if the given integer number is prime. Reminder, an integer number greater than 1 is prime if it divisible only by itself and by 1. In other words a prime number divided by any other natural number (besides 1 and itself) will have a non-zero remainder. Your task: Write a method called checkPrime(n) that will take an integer greater than 1 as an input, and return true if that integer is prime; otherwise, it should...