📌  相关文章
📜  Javasleep和yield方法的区别

📅  最后修改于: 2021-09-14 02:04:08             🧑  作者: Mango

在Java,如果一个线程不想在特定的时间内执行任何操作,那么我们应该使用 sleep() 方法,它会导致当前正在执行的线程停止指定的毫秒数。

句法 :

public static native void sleep( long ms) throws InterruptedException ;
// The above method put the thread in sleep for a specified number of millisecond
public static void sleep(long ms , int ns) throws InterruptedException
// The above method also put the thread in sleep for a specified number of milliseconds
// plus specified number of nanoseconds

方法一: sleep()方法

Java的每个 sleep() 方法都会抛出一个 InterruptedException ,这是一个已检查的异常,因此每当我们强制使用 sleep 方法时,我们应该通过 try-catch 或 throws 关键字来处理它,否则我们将得到编译时错误。

实现:在这里,我们在“ println ”语句之后让主线程休眠 5 秒。所以每张幻灯片需要 5 秒的时间来打印。

例子

Java
// Java Program to illustrate sleep method
 
// Importing all input output classes
import java.io.*;
// Importing all utility classes from
// java.util package
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        // Iterating using simple for loops
        for (int i = 0; i <= 10; i++) {
 
            // Printing the current thread slide
            System.out.println("slide-" + i);
 
            // Putting the main thread to sleep for 5 second
            Thread.sleep(5000);
        }
 
        // Here after every  5 seconds a slide will be
        // printed
    }
}


Java
// Java Program to illustrate yield() method
 
// Importing input output classes
import java.io.*;
// Importing all utility classes
import java.util.*;
 
// Class 1
// Helper class extending Thread class
 
// Creating a thread in our myThread class
// by extending the Thread class
 
class myThread extends Thread {
 
    // Method in helper class
    // Declaring run method
    public void run()
    {
 
        // Displaying the message
        System.out.println("Child Thread");
 
        // Calling yield() method
        Thread.yield();
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        // Creating a thread object in the main() method
        // of our helper class above
        myThread t = new myThread();
 
        // Starting the above thread created
        // using the start() method
        t.start();
 
        // Iterating using for loop
        // over custom taken size equals 5
        for (int i = 0; i < 5; i++) {
            // Display message
            System.out.println("Main Thread");
        }
    }
}


输出:

方法二: yield()方法

它会导致暂停当前正在执行的线程,以便有机会等待相同优先级的线程。如果没有等待线程或所有等待线程都具有低优先级,则同一线程可以继续执行。如果多个线程以相同的优先级等待,那么哪个等待线程将有机会我们不能说这取决于线程调度程序。线程何时再次获得机会也取决于线程调度程序。

句法:

public static native void yield( );

执行:

例子

Java

// Java Program to illustrate yield() method
 
// Importing input output classes
import java.io.*;
// Importing all utility classes
import java.util.*;
 
// Class 1
// Helper class extending Thread class
 
// Creating a thread in our myThread class
// by extending the Thread class
 
class myThread extends Thread {
 
    // Method in helper class
    // Declaring run method
    public void run()
    {
 
        // Displaying the message
        System.out.println("Child Thread");
 
        // Calling yield() method
        Thread.yield();
    }
}
 
// Class 2
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws InterruptedException
    {
 
        // Creating a thread object in the main() method
        // of our helper class above
        myThread t = new myThread();
 
        // Starting the above thread created
        // using the start() method
        t.start();
 
        // Iterating using for loop
        // over custom taken size equals 5
        for (int i = 0; i < 5; i++) {
            // Display message
            System.out.println("Main Thread");
        }
    }
}

输出说明:

在上面的程序中,如果我们注释Thread.yield() 行,两个线程将同时执行,我们不能指望哪个线程会先完成。如果我们不评论Thread.yield()方法,那么因为主线程将获得更多的机会,并且首先完成主线程的机会很高。

所以最后我们完成了这两种方法,让我们最后总结它们之间的差异。

Property                                 Yield Method                                   Sleep Method
Purpose If a thread wants to pause its execution to give chance for the remaining thread of the same priority then we should go for the yield method. If a thread doesn’t want to perform any operation for a particular amount of time then we should go for the sleep method 
Over-loading This method is not overloaded  The sleep method is overloaded.
Exception This method doesn’t throw an exception  This method throws  Interrupted Exception
Native  This method is native Amongst the two overloaded methods, only sleep(long ms) is overloaded while the other is not.
Give up monitors This method gives up the monitors. This method doesn’t cause the currently executing thread to give up monitors.