线程休眠 java_Java线程休眠和线程让步

线程休眠:我们希望人为地控制线程,使得正在执行的线程暂停,将CPU让给别的线程,我们可以使用静态方法sleep(long millis),该方法可以让当前正在执行的线程暂停一段时间,进入休眠等待状态。

线程让步:线程让步可以通过yield() 方法来实现,该方法和sleep()有点相似,都可以让当前正在运行的线程暂停,区别在于yield()方法不会阻塞该线程,他只是将线程转换成就绪状态,让系统调度器重新调度一次。当某个线程调用yield()方法之后,只有与当前线程优先级相同或者更高的线程才能获得执行的机会。

线程休眠简单实例:

public classThreadSleep {public static voidmain(String[] args) {new Thread(newSleepThread()).start();for(int i=1;i<=10;i++) {if(i == 5) {

System.out.println("mainThread start sleep!");try{

Thread.sleep(20000);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.println("mainThread is inputting:"+i);try{

Thread.sleep(500);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}class SleepThread implementsRunnable {

@Overridepublic voidrun() {//TODO Auto-generated method stub

for (int i = 0; i < 10; i++) {if (i == 3) {

System.out.println("deputyThread start sleep!");try{

Thread.sleep(5000);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

System.out.println("deputyThread is inputting:"+i);try{

Thread.sleep(500);

}catch(InterruptedException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

线程让步简单实例:

public class ThreadYield {

public static void main(String[] args) {

new Thread(new YieldThread(),"Thread A").start();

new Thread(new YieldThread(),"Thread B").start();

new Thread(new YieldThread(),"Thread C").start();

new Thread(new YieldThread(),"Thread E").start();

new Thread(new YieldThread(),"Thread F").start();

new Thread(new YieldThread(),"Thread G").start();

new Thread(new YieldThread(),"Thread H").start();

}

}

class YieldThread implements Runnable{

@Override

public void run() {

// TODO Auto-generated method stub

for(int i = 0;i <=10;i++) {

if(i == 4) {

System.out.println(Thread.currentThread().getName()+" that is inputting "+i+" has yielded!");

continue;

}

System.out.println(Thread.currentThread().getName()+" is inputting :"+i);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值