0

我正在用 java 中的多线程进行试验,基本上我想创建两个线程,并让它们计数到一个数字。

但是当他们到达大约一半时,他们会睡一段时间。所以我想在 FOR 循环中放置一个 IF 语句,看看它什么时候达到了一半,如果达到了,它就会让自己进入睡眠状态。

我正在运行单核 cpu atm,因为我在学校计算机上,所以理论上,当我让第一个线程进入睡眠状态时,第二个应该启动吗?

另外,是否可以让第一个线程从第二个线程进入睡眠状态,反之亦然?

4

5 回答 5

1

您可以使用Thread.sleep(int milliseconds)

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

As for making one thread pausing another, you could expose methods which the other threads can call to pause the execution of other threads.

Just like any other multi-threaded program, keep an eye out for race conditions.

As for your other question, single core processors should be able to run multiple threads, so the amount of cores (in this case) does not really matter.

于 2012-08-08T07:02:40.663 回答
0

线程只能使用Thread.sleep. 即使在单核 CPU 上运行时,JVM 也会为所有可运行的线程安排时间。如果您想更好地控制每个线程何时运行,您将需要查看java.util.concurrent包中的信号量和其他锁定/调度机制。

提出更具体的问题,以获得有关您在项目中遇到的问题的帮助。

于 2012-08-08T06:59:41.693 回答
0

当您开始让一个线程让另一个线程进入睡眠状态然后让自己进入睡眠状态时,您将非常接近竞争/死锁条件:

http://en.wikipedia.org/wiki/Deadlock#Necessary_conditions

于 2012-08-08T07:00:37.870 回答
0

I'd recommend you to have a look at this book It covers almost everything about java and concurrency/multithreading, including coding principles and many examples. Book For Conucurrency In java

于 2012-08-08T07:07:21.250 回答
0

For the first part of your question:

It's possible that the second thread may have finished by the time execution reaches the sleep() statement in the first thread. This is because the JVM allocates CPU time to threads not based on when in time each was started, but based on complex scheduling algorithms. The only thing that is guaranteed when you call Thread.sleep(1000) is that the thread WILL stop execution at that point for at least 1000 milliseconds.

The second part - putting one thread to sleep from another - has been addressed well by others. You need to watch out for race conditions.

于 2012-08-08T07:09:01.800 回答