英文:
Why Child Threads do not work when using while(true) loop in main thread without sleep?
问题
当在主线程中使用while(true)
循环并且使用Thread.sleep()
时,子线程可以正常工作,但如果从while
循环中移除sleep
方法,子线程将无法工作。我的意思是,线程定义了并行性,所以它应该工作?
public static void main(String[] args) {
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
System.out.println("我喜欢Java。");
Thread.sleep(500);
}
}
});
th1.start();
th2.start(); // 同样假设存在线程2
// 这是我的主线程
while (true) {
System.out.println("我是主线程。");
// 如果在这里使用Thread.sleep(200),则可以正常工作,但如果不使用,子线程将不会打印消息
}
}
我是Java新手,所以问题可能有点傻。答案将会有所帮助。
英文:
When using while(true) loop in main thread with Thread.sleep() the child threads works fine but if i remove sleep method from while loop the child threads do not work. I mean, thread defines parallelism so it should work ?
public static void main(String[] args) {
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i=0; i<50; i++) {
System.out.println("I love java.");
Thread.sleep(500);
}
}
});
th1.start();
th2.start(); // Similarly assume thread 2
// Here's my main thread
while(true) {
System.out.println("I am main thread.");
// If i use Thread.sleep(200) here, works fine but if not the child thread do not
print messages
}
}
I am new to java, so might be the question is bit silly. Answers will be helpful.
答案1
得分: 1
No, it works fine on both situations.
when you use Thread.sleep()
in main-thread the main thread executes slower, thus you can see the "I love java" message (because t1 executes first)
when you don't use Thread.sleep()
the main thread executes faster, so you can't see the "I love java" message. but it is there (on the first or second line of output)
debug the program to see more information. debugging shows the number of threads running currently and many more information
If you want to learn more about concurrency(multithreading) visit the link
https://www.baeldung.com/java-concurrency
英文:
No, it works fine on both situations.
when you use Thread.sleep()
in main-thread the main thread executes slower, thus you can see the "I love java" message (because t1 executes first)
when you don't use Thread.sleep()
the main thread executes faster, so you can't see the "I love java" message. but it is there (on the first or second line of output)
debug the program to see more information. debugging shows the number of threads running currently and many more information
If you want to learn more about concurrency(multithreading) visit the link
https://www.baeldung.com/java-concurrency
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论