El siguiente ejemplo muestra threads que llaman a yield() en cada pasada por el bucle. La ejecución muestra que, en el ordenador donde se ha ejecutado este ejemplo, la CPU practica una cierta equidad entre los threads disponibles para ejecutar.
class YieldingThread |
public class
YieldingThread extends Thread { private int contador = 3; public YieldingThread(int id) { super(String.valueOf(id)); } public String toString() { return "thread " +
getName() + ": " + contador; } public void run() { while (true) { System.out.println(this); if (contador-- == 0) return; yield(); } } public static void main(String[] args) { for (int id = 0; id < 5; id++) { YieldingThread yt = new
YieldingThread(id); yt.start(); } } } |
> java YieldingThread |
thread 0: 3 thread 1: 3 thread 2: 3 thread 3: 3 thread 4: 3 thread 0: 2 thread 1: 2 thread 2: 2 thread 3: 2 thread 4: 2 thread 0: 1 thread 1: 1 thread 2: 1 thread 3: 1 thread 4: 1 thread 0: 0 thread 1: 0 thread 2: 0 thread 3: 0 thread 4: 0 |
Temas relacionados