I pass the task ! But why? I enter the example and the the result is different. How is it correct?They are not sequentially.
input:
a
b
c
d
e
f
result :
a d f b c e
public class Solution {
public static volatile BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws InterruptedException {
Read3Strings t1 = new Read3Strings();
Read3Strings t2 = new Read3Strings();
//write your code here
t1.start();
t2.start();
t1.join();
t2.join();
t1.printResult();
t2.printResult();
}
//write your code here
public static class Read3Strings extends Thread {
ArrayList<String> arr = new ArrayList<>();
public void run() {
try {
for (int i = 0; i < 3; i++) {
arr.add(reader.readLine());
}
} catch (IOException e) {
System.out.println("Interrupted");
}
}
public void printResult() {
for (int i = 0; i < arr.size(); i++) {
System.out.print(arr.get(i) + " ");
}
}
}
}
My task is not correct but pass. Can someone try to explain me why ?
Under discussion
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
31 March 2021, 11:02
Two Read3Strings are running at the same time sharing the same resource, the BufferedReader reader. Cause BufferedReader is synchronized just one thread at a time can enter the reader. Let's say your t1 thread is first and reads in one string, then t2 is in waiting state. When t1 finishes, the JVM wakes up t2 and decides (randomly) between those two thread whose turn it is to enter next. So it could be t1 again but it might be t2. Only the JVM knows.
0
Zuz
1 April 2021, 19:52
Okey i undrestood that , but then can we make the result "a b c d e f", like t1 takes the first three letters and prints them and then stop its work. After this t2 starts and take the other input letters and prints " d e f".., i don't know if i explain what i am trying to do in the best way :D
0
Nouser
2 April 2021, 07:16
then you just need to run the threads one after the other. But usually that's not the use case for threads. For that purpose you just could write (sequntial) code in your main thread.
To do that with threads is easy as well, first thread: start, join, second thread: start, join
0
Zuz
2 April 2021, 15:02
Okey i got it ! Thank you !
0