多线程例子:yield
public class Test {public static void main(String[] args) {Thread t1 = new MyThread1();Thread t2 = new Thread(new MyRunnable());t2.start();t1.start();}}class MyThread1 extends Thread {public void run() {for (int i = 0; i < 10; i++) {System.out.println("线程1第" + i + "次执行!");//try {//Thread.sleep(1000);//} catch (InterruptedException e) {//// TODO Auto-generated catch block//e.printStackTrace();//}}}}class MyRunnable implements Runnable {public void run() {for (int i = 0; i < 10; i++) {System.out.println("线程2第" + i + "次执行!");Thread.yield();}}}
线程2第0次执行!线程1第0次执行!线程2第1次执行!线程1第1次执行!线程2第2次执行!线程1第2次执行!线程2第3次执行!线程1第3次执行!线程2第4次执行!线程1第4次执行!线程2第5次执行!线程1第5次执行!线程2第6次执行!线程2第7次执行!线程2第8次执行!线程1第6次执行!线程2第9次执行!线程1第7次执行!线程1第8次执行!线程1第9次执行!