Two threads separated at the same time and access to the same method

I am learning multithreading in Java, so now I am creating a classic Tortoise and Hare race application.

For those who are not familiar with this problem, there are basically two riders:

  • A hare that runs 100 meters in each cycle but has a 90% chance to rest instead of running
  • A turtle that runs 10 meters in each cycle but never rests

The winner will be the first to reach 1000 meters.

My code is as follows:

Main class:

public class THRace {

    static Thread hare      = new Thread(new ThreadRunner("Hare",       90, 100));
    static Thread tortoise  = new Thread(new ThreadRunner("Tortoise",   0,  10));

    public static void main(String[] args) {
        hare.start();
        tortoise.start();
    }

    public static void finished(Thread winner){
        if (winner.getName().equals("Hare")) tortoise.interrupt();
        else if (winner.getName().equals("Tortoise")) hare.interrupt();    
    }

}

ThreadRunner Class:

import java.util.Random;

public class ThreadRunner implements Runnable {

    private String name;
    private int rest, speed;

    public String getRacerName() {
        return name;
    }

    public ThreadRunner(String name, int rest, int speed) {
        this.name = name;
        this.rest = rest;
        this.speed = speed;
    }

    @Override
    public void run() {

        int meters = 0;
        Random rn = new Random();

        Thread ct = Thread.currentThread();
        ct.setName(name);

        while(!ct.isInterrupted()){
            if(rn.nextInt(100) + 1 > rest){
                meters += speed;
                System.out.println(this.name + ": " + meters);                
            }

            try {
                Thread.sleep(100);
            }catch (InterruptedException ex){
                return;
                //break;
            }

            if(meters >= 1000){
                System.out.println(this.name + ": I finished!");
                THRace.finished(ct);
                return;
            }

        }
    }

}

1000 , . , , , ( 1000 ), , , .

, , 0% , 1000 :

static Thread hare      = new Thread(new ThreadRunner("Hare",       0,  10));
static Thread tortoise  = new Thread(new ThreadRunner("Tortoise",   0,  10));

:

(...)
Tortoise: 950
Hare: 950
Hare: 960
Tortoise: 960
Tortoise: 970
Hare: 970
Tortoise: 980
Hare: 980
Tortoise: 990
Hare: 990
Tortoise: 1000
Hare: 1000
Hare: I finished!
Tortoise: I finished!

"" , ?

+4
1

, , . , .

synchronized public static void finished(Thread winner){
    if(winner.isInterrupted()) {
        // sorry, the other thread beat you here
        return;
    }

    if (winner.getName().equals("Hare")) tortoise.interrupt();
    else if (winner.getName().equals("Tortoise")) hare.interrupt();    
}

, , , , , , .

+7

Source: https://habr.com/ru/post/1584988/


All Articles