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

解决方案 »

  1.   

    yield跟终止线程没有关系,只是放弃当前的执行机会,使线程进入就绪状态而已.
      

  2.   

    Iceman's explaination is correct!
      

  3.   

    public static void yield()
    Causes the currently executing thread object to temporarily pause and allow other threads to execute. 导致当前执行的thread对象暂时中止执行,并且允许其它线程执行有时间看看apidoc还是有帮助的
      

  4.   

    t1 : 0 
    t2 : 0yield()以后,i的值为什么没有自增
      

  5.   

    i为0不是对的吗??
    你要i变成多少??yield()不会终止线程,仔细看看API DOC
    在你这个程序yield并没有什么用处
    yield只是在多线程运行,并繁忙的时候,让出当前的资源,使其他低优先级的线程能获得CPU时间
      

  6.   

    你先把thread的概念搞明白了,或许应该把类和变量的概念也搞明白了,第1行输出的是t1.i,第2行输出的是t2.i,为什么t2的成员变量要跟着t1的变量自增