class TestThreadMethod extends Thread{
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
for(int i=0; i <4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
Thread.yield(); //每次循环时,居然会i的值都会不自增???
}
}
}
class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start();
t2.start();
}
} 输出为:
--------------------Configuration: <Default>--------------------
t1 : 0
t2 : 0 //为什么上一次的yield没有把t1这个线程终止掉
t1 : 1
t2 : 1
t1 : 2
t2 : 2
t1 : 3
t2 : 3
public static int shareVar = 0;
public TestThreadMethod(String name){
super(name);
}
public synchronized void run(){
for(int i=0; i <4; i++){
System.out.print(Thread.currentThread().getName());
System.out.println(" : " + i);
Thread.yield(); //每次循环时,居然会i的值都会不自增???
}
}
}
class TestThread{
public static void main(String[] args){
TestThreadMethod t1 = new TestThreadMethod("t1");
TestThreadMethod t2 = new TestThreadMethod("t2");
t1.start();
t2.start();
}
} 输出为:
--------------------Configuration: <Default>--------------------
t1 : 0
t2 : 0 //为什么上一次的yield没有把t1这个线程终止掉
t1 : 1
t2 : 1
t1 : 2
t2 : 2
t1 : 3
t2 : 3
Causes the currently executing thread object to temporarily pause and allow other threads to execute. 导致当前执行的thread对象暂时中止执行,并且允许其它线程执行有时间看看apidoc还是有帮助的
t2 : 0yield()以后,i的值为什么没有自增
你要i变成多少??yield()不会终止线程,仔细看看API DOC
在你这个程序yield并没有什么用处
yield只是在多线程运行,并繁忙的时候,让出当前的资源,使其他低优先级的线程能获得CPU时间