简体   繁体   English

同步方法在线程中不起作用

[英]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.但是,当我删除 Game 类并在 Player 类中编写“等待”和“完成”方法时,“等待”方法会以某种方式被忽略。

How is it possible to get these methods inside the Player-class running?如何在 Player 类中运行这些方法?

wait() releases the lock, allowing other threads to enter the synchronized method. wait()释放锁,允许其他线程进入synchronized方法。

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.此方法导致当前线程(此处称为 T)将自己置于此 object 的等待集中,然后放弃此 object 的任何和所有同步声明。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM