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();
}
}
}
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();
}
}
}
所以你可以换成sleep,把sleep的时间稍微设置长一点,保证他在睡眠的时候另外一个线程能执行完10次循环就可以了
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!] ");
}
}
} }
}
}
为确保线程切换,在yield()后家一休眠1ms.
try
{
Thread.sleep(1);
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}我测试了一下,都能切换。如果楼主想一个线程输出10次,再切换到另一线程,那就需要加锁了。