fid
fid

Reputation: 72

Synchronized method won't work within the Thread

I'm trying out a simple program with threads and it works fine with those three clases:

public class Waiting {
    public static void main(String[] args) {
        Game game = new Game();
        for (int i = 0; i <= 1; i++) {
            new Thread(new Player(game, i)).start();
        }
    }
}
public class Player implements Runnable { 
    private Game game;
    private int number;
    boolean plays = false;

    public Player(Game game, int number) {
        this.game = game;
        this.number = number + 1;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println("starts number: " + number);
            considering(number);
            game.waiting(number);
            playing(number);
            game.finished(number);
        }
    }

    public void considering(int number) {
        try {
            System.out.println("player " + number + " considering");
            Thread.sleep((int) (Math.random() * 20000));
        } catch (Exception e) {
        }
    }

    public void playing(int number) {
        try {
            System.out.println("player " + number + " plays");
            Thread.sleep((int) (Math.random() * 20000));
        } catch (Exception e) {
        }
    }
}
public class Game {
    boolean plays = false;

    public Game() {

    }

    public synchronized void waiting(int number) {
        while (plays) {
            try {
                System.out.println("player " + number + " waiting");
                wait();
            } catch (Exception e) {
            }
        }
        plays = true;
    }

    public synchronized void finished(int number) {
        System.out.println("player " + number + " finished");
        plays = false;
        notify();
        System.out.println("----");
    }
}

But when I remove the Game-class and write methods "waiting" and "finished" inside Player-class the "waiting" method gets ignored somehow.

How is it possible to get these methods inside the Player-class running?

Upvotes: 0

Views: 36

Answers (1)

markspace
markspace

Reputation: 11030

wait() releases the lock, allowing other threads to enter the synchronized method.

This method causes the current thread (referred to here as T) to place itself in the wait set for this object and then to relinquish any and all synchronization claims on this object.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/lang/Object.html#wait(long,int)

Upvotes: 1

Related Questions