Java Tutorial #8 Creating a multithreaded dice roll App!

in #programming9 years ago

Previous tutorial https://steemit.com/java/@nicetea/java-tutorial-7

In this tutorial, we will creating a Dice class which is extending the thread class, as we can use multithreading then. The Dice class will have the function run() which will roll the dice 6 times and then print the average of the rolls. So let's get started with the code!

import java.util.Random;

public class Dice extends Thread {
    private Random random;
    private int rolls;
    private String name;
    
    public Dice(int rolls, String name){
        random = new Random();
        this.rolls = rolls;
        this.name = name;
    }

    public void run(){
        int sum = 0;
        int roll = 0;
        
        for(int i=0;i<this.rolls;i++){
            roll += random.nextInt(6)+1;
        }
        System.out.println("Average roll: "+roll/this.rolls);
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        
        Dice d = new Dice(7,"Thread 1");
        Dice d2 = new Dice(7,"Thread 2");
        d.start();
        d2.start();

    }

}

At the beginning we will declare, that we are extending the Thread class by using public class Dice extends Thread {, so we can actually use the threading functionality. Then we declare a few attributes, where the random attribute is actually an object from the class Random, which is used for randomization purposes.
As usually, we are going to create the standart constructor, which will initialize the random object, the amount of rolls and the name of the current object.
So now we are at the main part of this application, the for-loop inside the run() method.

        for(int i=0;i<this.rolls;i++){
            roll += random.nextInt(6)+1;
        }
        System.out.println("Average roll: "+roll/this.rolls);

Here, we are creating a loop, which will roll the dice until the amount of rolls, which are declared by the standart constructor is reached(this.rolls). With random.nextInt(6), we will create a random number from 0 - 5. Now as we need 6 numbers and no 0, we just add a 1 after it. So now we achieved the random number generator from 1 - 6! This random number is in every roll added to therollvariable. Once the loop has finished, the"Average roll"is printed out, by dividingrollwiththis.rolls``` (average).

The output will look like this:

Selection_035.png

Stay tuned!

Coin Marketplace

STEEM 0.05
TRX 0.32
JST 0.081
BTC 63253.25
ETH 1685.08
USDT 1.00
SBD 0.42