用java代码举例说明yeild怎么使用
时间: 2023-05-28 17:02:51 浏览: 132
yield是一种协作式的线程调度方法,可以让当前线程让出CPU时间片,让其他线程执行。下面是一个用Java代码实现yield的例子:
```
public class YieldExample implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " running " + i);
Thread.yield(); // 线程让出CPU时间片
}
}
public static void main(String[] args) {
YieldExample ye = new YieldExample();
Thread t1 = new Thread(ye, "Thread 1");
Thread t2 = new Thread(ye, "Thread 2");
Thread t3 = new Thread(ye, "Thread 3");
t1.start();
t2.start();
t3.start();
}
}
```
在上面的例子中,我们创建了3个线程并启动它们。每个线程都会运行run方法中的for循环,并且每次循环中都会调用Thread.yield()方法,让出CPU时间片给其他线程。运行结果可能是这样的:
```
Thread 1 running 0
Thread 2 running 0
Thread 3 running 0
Thread 2 running 1
Thread 1 running 1
Thread 3 running 1
Thread 2 running 2
Thread 3 running 2
Thread 1 running 2
Thread 2 running 3
Thread 3 running 3
Thread 1 running 3
Thread 2 running 4
Thread 3 running 4
Thread 1 running 4
```
从结果中可以看出,每个线程都有机会执行,而且没有明显的优先级差别。如果我们不使用yield方法,那么每个线程会一直执行for循环,直到结束。使用yield方法可以让线程更加协作,同时也减少了线程竞争导致的性能损失。
阅读全文