- Java.lang 包类
- Java.lang - 首页
- Java.lang - Boolean
- Java.lang - Byte
- Java.lang - Character
- Java.lang - Character.Subset
- Java.lang - Character.UnicodeBlock
- Java.lang - Class
- Java.lang - ClassLoader
- Java.lang - Compiler
- Java.lang - Double
- Java.lang - Enum
- Java.lang - Float
- Java.lang - InheritableThreadLocal
- Java.lang - Integer
- Java.lang - Long
- Java.lang - Math
- Java.lang - Number
- Java.lang - Object
- Java.lang - Package
- Java.lang - Process
- Java.lang - ProcessBuilder
- Java.lang - Runtime
- Java.lang - RuntimePermission
- Java.lang - SecurityManager
- Java.lang - Short
- Java.lang - StackTraceElement
- Java.lang - StrictMath
- Java.lang - String
- Java.lang - StringBuffer
- Java.lang - StringBuilder
- Java.lang - System
- Java.lang - Thread
- Java.lang - ThreadGroup
- Java.lang - ThreadLocal
- Java.lang - Throwable
- Java.lang - Void
- Java.lang 包其他内容
- Java.lang - 接口
- Java.lang - 错误
- Java.lang - 异常
- Java.lang 包有用资源
- Java.lang - 有用资源
- Java.lang - 讨论
Java 线程 yield() 方法
描述
Java Thread yield() 方法导致当前正在执行的线程对象暂时暂停,并允许其他线程执行。
声明
以下是 java.lang.Thread.yield() 方法的声明
public static void yield()
参数
无
返回值
此方法不返回值。
异常
示例:暂停当前正在执行的线程
以下示例演示了 java.lang.Thread.yield() 方法的使用。在此程序中,我们通过实现 Runnable 接口创建了一个线程类 ThreadDemo。在构造函数中,我们创建了一个新线程并使用 start() 方法启动它。
在 run() 方法中,我们启动了一个 for 循环,在第 5 次迭代中,使用 yield() 方法暂停当前正在执行的线程。run() 方法结束后,会打印一条包含当前线程详细信息的消息。在 main() 方法中,创建了三个 ThreadDemo 类的线程。
package com.tutorialspoint; public class ThreadDemo implements Runnable { Thread t; ThreadDemo(String str) { t = new Thread(this, str); // this will call run() function t.start(); } public void run() { for (int i = 0; i < 5; i++) { // yields control to another thread every 5 iterations if ((i % 5) == 0) { System.out.println(Thread.currentThread().getName() + " yielding control..."); /* causes the currently executing thread object to temporarily pause and allow other threads to execute */ Thread.yield(); } } System.out.println(Thread.currentThread().getName() + " has finished executing."); } public static void main(String[] args) { new ThreadDemo("Thread 1"); new ThreadDemo("Thread 2"); new ThreadDemo("Thread 3"); } }
输出
让我们编译并运行上述程序,这将产生以下结果:
Thread 1 yielding control... Thread 2 yielding control... Thread 3 yielding control... Thread 3 has finished executing. Thread 1 has finished executing. Thread 2 has finished executing.
java_lang_thread.htm
广告