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 {

 MyThread(String s){
super(s);
}

public void run(){

for(int i=1;i<=100;i++){
System.out.println( getName() + ": " + i );
if(i%10 == 0)
yield();

}

}

}

解决方案 »

  1.   

    因为yield只是说让当前线程暂停,并没有说暂停多久,所以假设第一个线程循环10次暂停了,那么第二个线程就该执行,如果这个时候第二个线程也循环完了10次,它也暂停了。那么接下来的就是随机的了。
    所以你可以换成sleep,把sleep的时间稍微设置长一点,保证他在睡眠的时候另外一个线程能执行完10次循环就可以了
      

  2.   

    不好意思,这样应该也会有错的。如果要保证10次切换的,估计只有用wait notify的办法才行咯。这里有段网站摘的代码,你借鉴一下:public class Test { public static void main(String args[]) {
    Thread[] threads = new Thread[2];
    for (int count = 0; count < threads.length; count++) {
    threads[count] = new ThreadCounter(count);
    threads[count].start();
    }
    } private static class ThreadCounter extends Thread {
    /**
     * 在没有同步的情况下,这个方法会打印出不定顺序的数字
     */
    public static void count() {
    for (int count = 1; count <= 5; count++)
    System.out.print(count + " ");
    } public static Object synchronizeVariable = "locking variable"; private int threadNo; public ThreadCounter(int threadNo) {
    this.threadNo = threadNo;
    } public void run() {
    countWithSync();
    } /**
     * 在有同步的情况下,能打印出这样顺序的数字: 1 1 2 2 3 3 4 4 5 5
     */
    private void countWithSync() {
    synchronized (synchronizeVariable) {
    for (int count = 1; count <= 5; count++) {
    System.out.println("[thread_" + threadNo + " print:]"
    + count + " ");
    synchronizeVariable.notifyAll(); if (count < 5) {
    System.out.println("[thread_" + threadNo
    + " sleep zzz...] "); try {
    synchronizeVariable.wait();
    } catch (InterruptedException error) {
    } System.out.println("[thread_" + threadNo + " wakup!] ");
    }
    }
    } }
    }
    }
      

  3.   

    如果简单就是逢10 切换线程,我测试了一下,基本上可以,很少有未切换的情况。
    为确保线程切换,在yield()后家一休眠1ms.
    try
    {
    Thread.sleep(1);
    }
    catch(InterruptedException ie)
    {
    ie.printStackTrace();
    }我测试了一下,都能切换。如果楼主想一个线程输出10次,再切换到另一线程,那就需要加锁了。