Почему код не работает? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Почему код не работает?

Не работает код: class MyClass implements Runnable { public static void main(String[ ] args) { Thread t = new Thread(new MyClass()); t.start(); } public void run() { System.out.println("Hello"); try { Thread.sleep(5000); } catch (InterruptedException e) { System.out.println("nooo!"); } System.out.println("Hello"); } }

17th May 2020, 12:41 PM
Дарина Котляренко
Дарина Котляренко - avatar
8 Answers
+ 1
It works. If you run in Sololearn, it can handle only maximum delay upto 2 seconds only.. due to limitation server execution time... So check code by Thread.sleep(1000);
17th May 2020, 12:47 PM
Jayakrishna 🇮🇳
+ 1
Yes. You have 2 outputs statements of hello print. That's why.. What is your expected output...?
17th May 2020, 12:52 PM
Jayakrishna 🇮🇳
+ 1
How can you saying that..? First one is you will get here.. Because there only single thread..... But thread are executed depending on its available time.. It's not sequencial, revise the thread topic again once...
17th May 2020, 1:10 PM
Jayakrishna 🇮🇳
+ 1
Add a output statement in try block before sleep then see it... It works as you expecting, since there only single thread.... But the delay is only in seconds then, you can't see it... When multiple treads are there, then when a thread is in sleeping or suspend state, then meanwhile other threads gets processor time and executed.. Previous thread goes into sleep.. Threads works like this, not exactly but a sample it is. So you can't see waiting in multiple threads., or sleep time is very less.. Run this in system with large delay then you can observe it clearly....
17th May 2020, 1:39 PM
Jayakrishna 🇮🇳
0
I tried. worked for 1 second, but not correctly. at first I waited 1 second and only then gave out two "Hello" at once
17th May 2020, 12:50 PM
Дарина Котляренко
Дарина Котляренко - avatar
0
1) hello. 2) wait 1 second. 3) hello
17th May 2020, 12:56 PM
Дарина Котляренко
Дарина Котляренко - avatar
0
I got: 1) wait 1 second. 2) hello. 3) hello.
17th May 2020, 12:57 PM
Дарина Котляренко
Дарина Котляренко - avatar
0
Seriously? I did not know. thank! how can one make it come out 1) action. 2) waiting. 3) action.?
17th May 2020, 1:14 PM
Дарина Котляренко
Дарина Котляренко - avatar