转载自:http://chenchendefeng.iteye.com/blog/457055
Thread.yield():
api中解释: 暂停当前正在执行的线程对象,并执行其他线程。
注意:这里的其他也包含当前线程,所以会出现以下结果。
- public class Test extends Thread {
- public static void main(String[] args) {
- for (int i = 1; i <= 2; i++) {
- new Test().start();
- }
- }
- public void run() {
- System.out.print("1");
- yield();
- System.out.print("2");
- }
- }
输出结果: 1122 或者 1212
public class ThreadYield extends Thread{
String name;
public ThreadYield(String name){
this.name = name;
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(name + " " + i);
Thread.yield();
}
}
}
public class MainClass {
public static void main(String[] args) {
//Thread.yield()
ThreadYield ty1 = new ThreadYield("t1");
ThreadYield ty2 = new ThreadYield("t2");
ty1.start();
ty2.start();
}
}
输出结果:
t1 0
t1 1
t1 2
t1 3
t2 0
t1 4
t2 1
t1 5
t2 2
t1 6
t2 3
t1 7
t2 4
t1 8
t2 5
t1 9
t2 6
t2 7
t2 8
t2 9