在JAVA并发程序的开发中,经常会用到这两个方法对程序进行测试,它们的相同点在于:
1. 都会暂缓执行当前线程;
2. 如果已经持有锁,那么在等待过程中都不会释放锁;
不同点在于:
1. Thread.sleep()可以精确指定休眠的时间,而Thread.yield()依赖于CPU的时间片划分,在我的电脑上大约为20微秒;
2. Thread.sleep()会抛出中断异常,且能被中断,而Thread.yield()不可以;
示例程序如下:
static class YieldLock extends Thread {
private Object monitor;
/**
* @param monitor
*/
@Inject
public YieldLock(Object monitor) {
this.monitor = monitor;
}
public void run() {
synchronized (monitor) {
while(true) {
Thread.yield();
}
}
}
}
static class MonitorLock extends Thread {
private Object monitor;
/**
* @param monitor
*/
@Inject
public MonitorLock(Object monitor) {
this.monitor = monitor;
}
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (monitor) {
System.out.println("我能拿到锁!");
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
final Object monitor = new Object();
new YieldLock(monitor).start();
// 下面的这个线程永远拿不到锁
// 所以也不会输出"我能拿到锁!"这句话
new MonitorLock(monitor).start();
}