java线程yield
时间: 2024-06-12 20:11:36 浏览: 72
yield()方法的作用是放弃当前的CPU资源,将它让给其他的任务去占用CPU执行时间。但是放弃的时间不确定,有可能刚刚放弃又马上获得CPU时间片。注意调用yield方法并不会让线程进入阻塞状态,而是让线程重回就绪状态,它只需要等待重新获取CPU执行时间。yield方法只能让拥有相同优先级的线程有获取CPU执行时间的机会。同时,yield方法也不能保证一定会让其他线程执行,因为CPU的调度是不可控的。下面是一个简单的例子:
```
public class TestYield {
public static void main(String[] args) {
MyThread t1 = new MyThread("t1");
MyThread t2 = new MyThread("t2");
t1.start();
t2.start();
}
}
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running " + i);
Thread.yield();
}
}
}
```
输出结果可能是:
```
t1 is running 0
t2 is running 0
t1 is running 1
t2 is running 1
t1 is running 2
t2 is running 2
t1 is running 3
t2 is running 3
1 is running 4
t2 is running 4
```
阅读全文