In: Computer Science
Need to make Java code as following:
Create a dice playing threading program to do the following:
1. Start a thread for a process to simulate a computer rolling a die 1000 times.
2. Start another thread for a process to simulate a user rolling a die 1000 times.
3. Keep track of rolls for user and computer in an array(s).
4. Display on screen when the computer thread starts, the rolls, and when the computer thread ends.
5. Display on screen when the user thread starts, the rolls, and when the user thread ends.
6. Once the rolls are completed for both computer and user, use the array(s) to count number of computer wins, number of user wins, and ties. Each element of one array is compared to each element in the other array by index. So computerRoll[0] is compared to userRoll[0], etc.
import java.util.Random; public class DiceRoll { static int userRolls[] = new int[1000]; static int computerRolls[] = new int[1000]; static class UserThread implements Runnable { @Override public void run() { System.out.println("User thread started."); Random random = new Random(); for (int i = 0; i < 1000; i++) { userRolls[i] = random.nextInt(6) + 1; System.out.println("User dice rolled, Output: " + userRolls[i]); } System.out.println("User thread ended."); } } static class ComputerThread implements Runnable { @Override public void run() { System.out.println("Computer thread started."); Random random = new Random(); for (int i = 0; i < 1000; i++) { computerRolls[i] = random.nextInt(6) + 1; System.out.println("Computer dice rolled, Output: " + computerRolls[i]); } System.out.println("Computer thread ended."); } } public static void main(String[] args) throws InterruptedException { Thread computerThread = new Thread(new ComputerThread()); Thread userThread = new Thread(new UserThread()); computerThread.start(); userThread.start(); computerThread.join(); userThread.join(); int computerWins = 0, userWins = 0, ties = 0; for (int i = 0; i < 1000; i++) { if (computerRolls[i] > userRolls[i]) computerWins++; else if (computerRolls[i] < userRolls[i]) userWins++; else ties++; } System.out.println("Computer Wins: " + computerWins); System.out.println("User Wins: " + userWins); System.out.println("Ties: " + ties); } }