简体   繁体   English

一次只执行一个线程,如何同时执行多个任务?

[英]At a time only one thread is executed, how to execute multiple tasks simultaneously?

Click http://www.javatpoint.com/sleep()-method 点击http://www.javatpoint.com/sleep()-方法

It's tutorial said only when a thread is sleep, the another thread will be picked up by thread scheduler. 它的教程说,只有当一个线程处于睡眠状态时,另一个线程才会被线程调度程序拾取。 So only one thread is working each time? 那么每次只有一个线程在工作吗?

On a system with multiple cores, both threads would start at about the same time (depending on how long it takes to create a thread). 在具有多个内核的系统上,两个线程大约在同一时间启动(取决于创建线程需要多长时间)。

The effect of the sleeps could end up "synchronizing" the threads, so that both threads would be running and/or sleeping at the same (or very nearly the same) time (depends on the OS). 睡眠的结果可能最终导致线程“同步”,因此两个线程将在相同(或几乎相同)的时间(取决于操作系统)运行和/或睡眠。 The "synchronizing" would occur if both threads got started within one system timer tick of each other. 如果两个线程都在彼此的一个系统计时器间隔内启动,则将发生“同步”。 For Windows, the timer normally runs at 64hz, or 15.625 ms per tick, so both threads would exit the sleep state every 32 timer ticks (500 ms) on the same tick. 对于Windows,该计时器通常以64hz或每滴答15.625 ms的速度运行,因此两个线程将在同一滴答上每32个计时器滴答(500 ms)退出睡眠状态。

During a sleep, the OS can run other threads on the same core as the thread that did the sleep. 在睡眠期间,操作系统可以在与执行睡眠的线程相同的内核上运行其他线程。 In this case, unless the system only has a single core (and no hyperthreading), the two threads run at the same time. 在这种情况下,除非系统只有一个核心(并且没有超线程),否则两个线程将同时运行。

I assume that System.out.println(i) is multi-threaded safe (so that two instances at the same time from two threads doesn't cause a problem). 我假设System.out.println(i)是多线程安全的(因此来自两个线程的两个实例同时不会引起问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何同时执行三个线程? - How to execute three thread simultaneously? 调度:在spring boot中只执行一次任务 - Scheduling: execute tasks only one time in spring boot 是否可以只执行一次而不是在所有线程池中执行计划任务? - Is it possible to execute scheduled task only one time and not in all thread pool? 如何在java swing中同时执行两个线程? - how to execute two thread simultaneously in java swing? Java线程:如何同时执行一条语句 - Java Thread: How to execute a statement simultaneously 一个线程可以同时处理多个请求吗? - Can one thread handles multiple requests simultaneously? Quartz Job由每台群集计算机同时执行多次,而不是整个群集由一台计算机一次执行 - Quartz Job executed multiple times simultaneously by each cluster machine, rather than one time by one machine for the entire cluster 如何限制任务,以便一次只运行一个任务,然后忽略休息 - How to throttle tasks such that only one runs at a time and rest are ignored 如何仅执行一个线程并接收Future而无需创建ExecutorService? - How to execute only one thread and receive a Future without creating an ExecutorService? rxJava:如何同时执行多个Maybe - rxJava: how to execute multiple Maybes simultaneously
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM