2010-08-21 17 views
7

sleep()是Thread类的静态方法。从多线程调用时它是如何工作的。以及它如何找出当前的执行线程。 ?Thread.sleep()在多线程调用时如何工作

或可能是一个更一般的问题将是如何从不同的线程调用静态方法?会不会有任何并发​​问题?

回答

6

它是如何计算出当前的 执行线程?

它不是必须的。它只是调用操作系统,它总是睡觉调用它的线程。

+1

+1:我找不到正确的单词。 – 2010-08-28 07:16:49

5

sleep方法睡眠当前线程,所以如果您从多个线程调用它,它将睡眠每个线程。另外还有一个静态方法currentThread,它可以让你获得当前正在执行的线程。

-1

Thread.sleep(long)本身在java.lang.Thread类中实现。下面是它的API文档的一部分:

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. 

睡眠方法休眠调用它的线程(基于EJP的评论) 确定当前执行的线程(调用它,并导致它睡觉)。 Java方法可以通过调用Thread.currentThread()

来确定哪个线程正在执行它。可以同时从任意数量的线程调用方法(静态或非静态)。只要您的方法是thread safe,Threre就不会有任何并发​​问题。 只有当多个线程正在修改类或实例的内部状态而未正确同步时,您将遇到问题。

+0

@naikus Implentation说,睡眠是天然的方法。任何想法本机代码如何确定什么线程睡觉? – YoK 2010-08-21 06:48:50

+0

@Naikus。我想知道的是,静态方法中的代码如何在线程范围内运行。会有每个方法的副本加载到线程的堆栈吗? – JWhiz 2010-08-21 06:56:19

+0

@YoK,我不确定,但也许它调用另一个本地方法Thread.currentThread();)。我确定你知道这件事。 – naikus 2010-08-21 07:04:46

0

一个更一般的问题将是如何从不同的线程调用静态方法?会不会有任何并发​​问题?

如果一个或多个线程在另一个线程使用相同状态时修改共享状态,那么只有潜在的并发问题。 sleep()方法没有共享状态。

-1

当虚拟机遇到sleep(long) -statement时,它将中断正在运行的线程。 “当前线程”在那一刻始终是调用Thread.sleep()的线程。然后它说:

嘿!在这个线程中没有任何事情要做(因为我必须等待)。我将继续其他主题。

更改线程被称为“收益”。 (注意:你可以通过自己致电Thread.yield();

所以,它不需要知道当前的线程是什么。它始终是调用sleep()的线程。 注意:您可以通过调用Thread.currentThread();

简单例子得到当前线程:

// here it is 0 millis 
blahblah(); // do some stuff 
// here it is 2 millis 
new Thread(new MyRunnable()).start(); // We start an other thread 
// here it is 2 millis 
Thread.sleep(1000); 
// here it is 1002 millis 

MyRunnablerun()方法:Thread类的

// here it is 2 millis; because we got started at 2 millis 
blahblah2(); // Do some other stuff 
// here it is 25 millis; 
Thread.sleep(300); // after calling this line the two threads are sleeping... 
// here it is 325 millis; 
... // some stuff 
// here it is 328 millis; 
return; // we are done; 
+0

没有'中断'。 – EJP 2010-08-21 12:21:52