yield实现线程交替运行

yield的意思是放手,放弃,一个线程调用yield意味着它要告诉虚拟机自己乐意让其它线程占用自己的位置。

class Producer extends Thread  
{  
    public void run()  
    {  
        for(int i = 0; i < 5; i++)  
        {  
            System.out.println("i am producer: producerd item " + i);  
            Thread.yield();  
        }  
    }  
}  
  
class Consumer extends Thread  
{  
    public void run()  
    {  
        for(int i = 0; i < 5; i++)  
        {  
            System.out.println("i am Consumer: Consumed item " + i);  
            Thread.yield();  
        }  
    }  
}  
public class JoinAndYieldTestDemo   
{  
  
    /** 
     * @param args 
     */  
    public static void main(String[] args)   
    {  
          
        Thread producer = new Producer();  
        Thread consumer = new Consumer();  
          
        producer.setPriority(Thread.MIN_PRIORITY);  
        consumer.setPriority(Thread.MAX_PRIORITY);  
          
        producer.start();  
        consumer.start();  
    }  
  
}  

 

posted on 2016-07-23 13:07  乐可2016  阅读(221)  评论(0编辑  收藏  举报