线程的礼让

本文深入探讨了Java中线程礼让的概念,通过具体代码示例解释了如何使用yield()方法使当前线程放弃CPU资源,让相同或更高优先级的线程有机会运行。通过对比两个不同线程的行为,展示了线程礼让的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的礼让<?xml version="1.0" encoding="UTF-8"?>
线程礼让是指当前正在运行的线程退出运行状态,暂时将运行权让给优先级相同或更高的线程。

调用yield()方法实现礼让,他会将当前程序转到就绪状态。

yield()方法不抛出任何异常。

class Test1 implements Runnable {
     public void run (){
     for ( int i = 1 ; i <= 5 ; i ++){
    System . out . println ( "running thread: " + Thread . currentThread (). getName () + ", i = " + i );
    Thread . currentThread (). yield ();
     }
     }
}
class Test2 implements Runnable {
     public void run (){
     for ( int i = 1 ; i <= 5 ; i ++){
     System . out . println ( "running thread: " + Thread . currentThread (). getName () + ", i = " + i );
     }
     }
}
public class ThreadDemo11 {
     public static void main ( String [] args ){
    Test1 t1 = new Test1 ();
    Thread th1 = new Thread ( t1 , "Thread-1" );
    Test2 t2 = new Test2 ();
    Thread th2 = new Thread ( t2 , "Thread-2" );
    th1 . start ();
    th2 . start ();
    }
}

                         271439048295630.png

从理论上,t1线程运行的几率要小于t2线程,因为t1总是让其它线程先执行




转载于:https://www.cnblogs.com/ZhangJinkun/p/fd09e2ebe4c6017f25f63652ff08b93a.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值