Посмотрите на это, я изменил ваш код с использованием многопоточности, и теперь он может работать так, как вы думаете.
Вот код:
package exercise.dillo;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
static Scanner input = new Scanner(System.in);
public static Dillo arma = new Dillo("Arma", 50, false);
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
exec.execute(new DilloTask(arma));
while (true) {
// arma.stats();
// arma.hunger();
int food = input.nextInt();
arma.feed(food);
// arma.dead();
}
}
}
class DilloTask implements Runnable {
private Dillo dillo;
private Random rand = new Random();
public DilloTask(Dillo dillo) {
this.dillo = dillo;
}
@Override
public void run() {
try {
while (!Thread.interrupted()) {
TimeUnit.MILLISECONDS.sleep(1000 + rand.nextInt(1000));
dillo.stats();
dillo.hunger();
dillo.dead();
}
} catch (InterruptedException e) {
System.out.println("DilloTask is interrupted");
}
}
}
И класс Dillo, просто внесите несколько изменений с синхронизированным ключевым словом.
package exercise.dillo;
public class Dillo {
private double weight;
private boolean isDead;
private String name;
public Dillo(String name, double weight, boolean isDead) {
this.name = name;
this.weight = weight;
this.isDead = isDead;
}
public double getWeight() {
return this.weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public synchronized void stats() {
System.out.println(name + " is " + weight + " pounds!");
}
public synchronized void feed(int foodAmnt) {
this.weight += foodAmnt;
System.out.println(name + " has grown by " + foodAmnt + " pounds!");
System.out.println(name + " is now " + weight + " pounds!");
}
public synchronized void dead() {
if (this.weight >= 75) {
isDead = true;
System.out.println(this.name + " is too fat and died!");
System.exit(0);
} else if (this.weight <= 25) {
isDead = true;
System.out.println(this.name + " is too skinny and died!");
System.exit(0);
}
}
public synchronized void hunger() {
this.weight -= 1;
System.out.println(this.weight);
}
}
Теперь результат выглядит так:
Arma is 50.0 pounds!
49.0
Arma is 49.0 pounds!
48.0
Arma is 48.0 pounds!
47.0
Arma is 47.0 pounds!
46.0
10Arma is 46.0 pounds!
45.0
Arma has grown by 10 pounds!
Arma is now 55.0 pounds!
Arma is 55.0 pounds!
54.0
....
Arma is 37.0 pounds!
36.0
-2
Arma has grown by -2 pounds!
Arma is now 34.0 pounds!
Arma is 34.0 pounds!
33.0
-Arma is 33.0 pounds!
32.0
3
Arma has grown by -3 pounds!
Arma is now 29.0 pounds!
Arma is 29.0 pounds!
28.0
Arma is 28.0 pounds!
27.0
Arma is 27.0 pounds!
26.0
Arma is 26.0 pounds!
25.0
Arma is too skinny and died!
Я использую класс Random для бесконечного голодания. Вы можете отменить его или сбросить
время голодное. В этом примере используются два потока, один из которых является основным, а другой - другим.
запустите DilloTask, чтобы при вводе числа не блокировать процедуру.