zoukankan      html  css  js  c++  java
  • 线程中yield的用法

    yield方法是 Thread类的方法

    /**
    * Causes the currently executing thread object to temporarily pause
    * and allow other threads to execute.
    */
    public static native void yield();

    从注释上来看 

    *使当前正在执行的线程对象暂时暂停
    *并允许其他线程执行。

    写个demo测试一下

    public class TestYield {
    public static void main(String[] args) {
    Thread t1 = new Thread(new Runnable(){
    public void run(){
    System.out.println("开始抢占线程1:"+Thread.currentThread().getName());
    Thread.yield();
    System.out.println("线程运行结束1:"+Thread.currentThread().getName());
    }
    });
    Thread t2 = new Thread(new Runnable(){
    public void run(){
    System.out.println("开始抢占线程2:"+Thread.currentThread().getName());
    System.out.println("线程运行结束2:"+Thread.currentThread().getName());
    }
    });
    t1.start();
    t2.start();
    }
    }

    运行结果:

    开始抢占线程1:Thread-0
    开始抢占线程2:Thread-1
    线程运行结束2:Thread-1
    线程运行结束1:Thread-0

    如果注释掉  Thread.yield();

    开始抢占线程2:Thread-1
    线程运行结束2:Thread-1
    开始抢占线程1:Thread-0
    线程运行结束1:Thread-0

  • 相关阅读:
    Java 概述
    vue组件事件
    小程序注册
    小程序基础知识梳理
    小程序简介
    公众号
    jeecg-boot
    小程序背景图
    bootstrap-select采坑
    存取cookie
  • 原文地址:https://www.cnblogs.com/zjf6666/p/9375745.html
Copyright © 2011-2022 走看看