本文主要是介绍线程睡眠sleep()方法和线程让步yield()方法的主要区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
import java.util.*;
public class SleepTest
{
public static void main(String[] args) throws Exception
{
for (int i=0; i<10; i++)
{
System.out.println("当前时间:" + new Date());
//调用sleep()方法让当前线程暂停2s
Thread.sleep(2000);
}
}
}
运行结果:
D:\mytest\Thread>javac SleepTest.java
D:\mytest\Thread>java SleepTest
当前时间:Mon Mar 24 12:36:02 CST 2014
当前时间:Mon Mar 24 12:36:04 CST 2014
当前时间:Mon Mar 24 12:36:06 CST 2014
当前时间:Mon Mar 24 12:36:08 CST 2014
当前时间:Mon Mar 24 12:36:10 CST 2014
当前时间:Mon Mar 24 12:36:12 CST 2014
当前时间:Mon Mar 24 12:36:14 CST 2014
当前时间:Mon Mar 24 12:36:16 CST 2014
当前时间:Mon Mar 24 12:36:18 CST 2014
当前时间:Mon Mar 24 12:36:20 CST 2014
public class TestYield {
public static void main(String[] args) {
MyThread3 t1 = new MyThread3("t1");
MyThread3 t2 = new MyThread3("t2");
t1.start(); t2.start();
}
}
class MyThread3 extends Thread {
MyThread3(String s){super(s);}
public void run(){
for(int i =1;i<=40;i++){
System.out.println(getName()+": "+i);
if(i%10==0){
yield();
}
}
}
}
运行结果:
D:\mytest\Thread>javac TestYield.java
D:\mytest\Thread>java TestYield
t1: 1
t1: 2
t1: 3
t1: 4
t1: 5
t1: 6
t1: 7
t1: 8
t1: 9
t1: 10
t2: 1
t2: 2
t2: 3
t2: 4
t2: 5
t2: 6
t2: 7
t2: 8
t2: 9
t2: 10
t1: 11
t1: 12
t1: 13
t1: 14
t1: 15
t1: 16
t1: 17
t1: 18
t1: 19
t1: 20
t1: 21
t1: 22
t1: 23
t1: 24
t1: 25
t1: 26
t1: 27
t1: 28
t1: 29
t1: 30
t1: 31
t1: 32
t1: 33
t1: 34
t1: 35
t1: 36
t1: 37
t1: 38
t1: 39
t1: 40
t2: 11
t2: 12
t2: 13
t2: 14
t2: 15
t2: 16
t2: 17
t2: 18
t2: 19
t2: 20
t2: 21
t2: 22
t2: 23
t2: 24
t2: 25
t2: 26
t2: 27
t2: 28
t2: 29
t2: 30
t2: 31
t2: 32
t2: 33
t2: 34
t2: 35
t2: 36
t2: 37
t2: 38
t2: 39
t2: 40
关于sleep()方法和yield()方法的区别如下:
1.sleep()方法暂停当前线程后,会给其他线程执行机会,不会理会其他线程的优先级;但yield()方法只会给优先级相同,或优先级更高的线程执行机会。
2.sleep()方法会将线程转入阻塞状态,直到经过阻塞时间才会转入就绪状态;而yield()方法不会将线程转入阻塞状态,它只是强制当前线程进入就绪状态。因此完全有可能某个线程调用yield()方法暂停之后,立即再次获得处理器资源被执行。
3.sleep()方法声明抛出了InterruptedException异常,所以调用sleep()方法时要么捕捉该异常,要么显式声明抛出该异常;而yield()方法则没有声明抛出任何异常。
4.sleep()方法比yield()方法有更好的可移植性,通常不建议使用yield()方法来控制并发线程的执行。
这篇关于线程睡眠sleep()方法和线程让步yield()方法的主要区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!