yield与sleep类似,只是不能指定暂停多长时间,并且只能让同优先级的线程有执行的机会,让位时间不固定。

/*
    yield使用
*/
public class ThreadTest04 
{
    public static void main(String[] args) throws Exception
    {
        Thread t1 = new Thread(new Processor());
        t1.setName("t1");
        t1.start();

        //主线程
        for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+"--->"+i);
        }
    }
}

class Processor implements Runnable
{
    public void run(){
        for(int i=1;i<=100;i++){
            System.out.println(Thread.currentThread().getName()+"--->"+i);
            if(i % 20 == 0){
                Thread.yield();
            }                
        }
    }
}

 

相关文章:

  • 2021-09-08
  • 2022-02-04
  • 2022-12-23
  • 2021-12-07
  • 2022-01-08
  • 2022-12-23
  • 2022-02-21
  • 2022-01-23
猜你喜欢
  • 2022-02-28
  • 2021-10-04
  • 2021-09-23
  • 2022-02-02
  • 2022-12-23
  • 2021-06-30
  • 2021-08-22
相关资源
相似解决方案