Answer the question
In order to leave comments, you need to log in
Multithreading not terminating?
This code freezes, if you change the value of totalCountSpeeches to 2000 - it ends.
I have a few assumptions, but they are just guesses, as there is not enough knowledge of how the JVM works with multiple threads...
public class Solution {
public static int totalCountSpeeches = 200;
public static int soundsInOneSpeech = 1000000;
public static void main(String[] args) throws InterruptedException {
Politic ivanov = new Politic("Иванов");
Politic petrov = new Politic("Петров");
Politic sidorov = new Politic("Сидоров");
while (ivanov.getCountSpeaches() + petrov.getCountSpeaches() + sidorov.getCountSpeaches() < totalCountSpeeches) {
}
System.out.println(ivanov);
System.out.println(petrov);
System.out.println(sidorov);
}
public static class Politic extends Thread {
private int countSounds;
public Politic(String name) {
super(name);
start();
}
public void run() {
while (countSounds < totalCountSpeeches * soundsInOneSpeech) {
countSounds++;
}
}
public int getCountSpeaches() {
return countSounds / soundsInOneSpeech;
}
@Override
public String toString() {
return String.format("%s сказал речь %d раз", getName(), getCountSpeaches());
}
}
}
Answer the question
In order to leave comments, you need to log in
Runnable picture will not change.
First, comments on the code
while (ivanov.getCountSpeaches() + petrov.getCountSpeaches() + sidorov.getCountSpeaches() < totalCountSpeeches) {
}
Well, why do you think that you "hung"? Add debug printing, see if your code does something or not. There can be many problems, ranging from resource race and int overflow, for example.
while (countSounds < totalCountSpeeches * soundsInOneSpeech) {
countSounds++;
System.out.println("name -> " + this.getName() + ", " + "count -> " + countSounds);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question