yield、sleep、join、interrupt
yield()
概述
A hint to the scheduler that the current thread is willing to yield its current use of a processor. The scheduler is free to ignore this hint.
源码注释中这句话的意思是:向线程调度器表示当前线程放弃当前对处理器的使用。调度器可能忽略这个提示。
通俗的说就是当让前的线程从运行状态
进入到就绪状态
,CPU重新进行调度,但是不保证调用yield后其他线程就一定能抢到执行时间,即使其他线程和调用yield具有相同优先级。yield()不会释放锁!
例子
public class Demo6 implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Thread.yield();
System.out.println(Thread.currentThread().getName() + "continue");
}
}
public static void main(String[] args) throws Exception {
Demo6 demo6 = new Demo6();
Thread t1 = new Thread(demo6);
//设置t1的优先级和main方法相同
t1.setPriority(5);
t1.start();
for (int i = 0; i < 10; i++) {
Thread.yield();
System.out.println(Thread.currentThread().getName() + "continue");
}
}
}
运行结果:
maincontinue
Thread-0continue
Thread-0continue
maincontinue
Thread-0continue
maincontinue
maincontinue
maincontinue
maincontinue
maincontinue
maincontinue
maincontinue
maincontinue
Thread-0continue
Thread-0continue
Thread-0continue
Thread-0continue
Thread-0continue
Thread-0continue
Thread-0continue
运行的结果并没有规律,说明在yield后调度器不一定会将时间片分配给其他线程执行,否则结果应该是一条t1线程输出一条Main线程输出。
例2:
public class Demo5 implements Runnable {
private static final Object obj = new Object();
@Override
public void run() {
synchronized (obj) {
try {
System.out.println(Thread.currentThread().getName() + "-start");
System.out.println(Thread.currentThread().getName() + "-end");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Demo5 demo5 = new Demo5();
Thread t1 = new Thread(demo5);
synchronized (obj) {
System.out.println(Thread.currentThread().getName() + "-start");
t1.start();
Thread.yield();
System.out.println(Thread.currentThread().getName() + "-end");
}
}
}
输出结果:
main-start
main-end
Thread-0-start
Thread-0-end
由输出结果可知,main线程调用yield()后并没有释放锁,直到main线程运行完同步代码块释放锁后t1才开始执行,所以yield()不会释放锁。
yield()和wait()的区别
- wait()是将线程从运行状态切换到
阻塞状态
,而yield()是将线程从运行状态切换到就绪状态
- wait()会释放持有的对象的同步锁,