Java 当从多个线程调用Thread.sleep()时,它是如何工作的

Java 当从多个线程调用Thread.sleep()时,它是如何工作的,java,multithreading,static,synchronization,Java,Multithreading,Static,Synchronization,sleep()是类Thread的静态方法。当从多个线程调用时,它是如何工作的。它如何计算当前的执行线程 或者更一般的问题是,如何从不同线程调用静态方法?不会有任何并发问题吗?sleep方法睡眠当前线程,因此如果您从多个线程调用它,它将睡眠其中的每个线程。还有一个静态方法,它允许您获取当前正在执行的线程。thread.sleep(long)是在java.lang.thread类中本机实现的。以下是其API文档的一部分: Causes the currently executing thread

sleep()是类Thread的静态方法。当从多个线程调用时,它是如何工作的。它如何计算当前的执行线程


或者更一般的问题是,如何从不同线程调用静态方法?不会有任何并发问题吗?

sleep方法睡眠当前线程,因此如果您从多个线程调用它,它将睡眠其中的每个线程。还有一个静态方法,它允许您获取当前正在执行的线程。

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.
sleep方法使调用它的线程休眠。(基于EJP的注释)确定当前正在执行的线程(调用它并使其休眠)。Java方法可以通过调用
thread.currentThread()

方法(静态或非静态)可以从任意数量的线程同时调用。只要您的方法有效,就不会有任何并发问题。 只有当多个线程在没有正确同步的情况下修改类或实例的内部状态时,才会出现问题

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

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

它是如何计算电流的 执行线索


没必要。它只调用操作系统,操作系统总是休眠调用它的线程。

当虚拟机遇到
sleep(long)
-语句时,它将中断当前正在运行的线程。此时的“当前线程”总是调用
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
MyRunnable
its
run()
方法:

// 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;

@Thread类的naikus实现称睡眠是本机方法。知道本机代码如何决定要睡眠的线程吗?@Naikus。我想知道的是,静态方法中的代码是如何在线程范围内运行的。是否会有每个方法的副本加载到线程的堆栈中?@YoK,我不确定,但可能它调用另一个本机方法thread.currentThread();)。我肯定你知道。@JWhiz不,不会有方法的任何副本,instaead对于java方法,堆栈对于每个方法调用都有一个“堆栈框架”,用于存储方法调用的状态。但这只适用于java方法,而不是本机方法。“sleep方法确定当前正在执行的线程(调用它并使其休眠)”。那是不对的。除了调用操作系统的sleep()系统调用外,Thread.sleep()不需要执行任何操作。sleep()是一个系统调用,总是导致当前线程休眠。