线程的资源出让,sleep与yield
作者:bin* 线程的sleep
* 线程的yield
* 线程的优先级
public class Part4 { private final static String PREFIX = "MARK-"; public static void main(String[] args) throws Exception{ threadSleep(); threadYield(); threadPriority(); } /** * 线程sleep * @throws Exception */ private static void threadSleep() throws Exception{ new Thread(() -> { try { //原方法 Thread.sleep(100); //推荐使用封装的TimeUnit方法 TimeUnit.MILLISECONDS.sleep(100); }catch (Exception e) { } }).start(); } /** * yield 属于启发式 * 1、调用yield方法会让线程从 running 状态 变成 runnable 状态 * 2、yield方法在cpu资源紧张时会表现的比较明显,即「让」资源给其他进程 * 3、sleep方法会暂停当前线程,让cpu资源给其他线程 * * @throws Exception */ private static void threadYield() throws Exception { new Thread(() -> { try { //告诉处理器,可以让出资源 Thread.yield(); }catch (Exception e) { } }).start(); } /** * 执行优先级 * 1、如果cpu资源紧张,那么程序会优先分配时间片给优先级高的线程 * 2、线程默认优先级为5,即main方法启动时的优先级, * 3、子线程优先级继承父线程优先级 */ private static void threadPriority(){ Thread thread = new Thread(() -> { try { //告诉处理器,可以让出资源 Thread.yield(); }catch (Exception e) { } }); //设置优先级 thread.setPriority(10); thread.start(); } }