为了账号安全,请及时绑定邮箱和手机立即绑定

为什么运行时前几次那么乱呢,一会先生一会女士。不规律

package com.xuanxuan;


public class Actor extends Thread {

public void run() {

System.out.println(getName()+"是一个演员");

int count=0;

boolean keepRuning=true;

while(keepRuning) {

System.out.println(getName()+"登台演出"+(++count));

if(count==100) {

keepRuning=false;

}

if(count%10==0) {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

System.out.println(getName()+"演出结束了");

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Thread actor=new Actor();

actor.setName("先生");

Thread actressThread=new Thread(new Actress(),"xiaoxiaoxiao女士");

actor.start();

actressThread.start();

}


}

class Actress implements Runnable{

public void run() {

System.out.println(Thread.currentThread().getName()+"是一个演员");

int count=0;

boolean keepRuning=true;

while(keepRuning) {

System.out.println(Thread.currentThread().getName()+"登台演出"+(++count));

if(count==100) {

keepRuning=false;

}

if(count%10==0) {

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

System.out.println(Thread.currentThread().getName()+"演出结束了");

}

}

https://img1.sycdn.imooc.com//5cbed89900010a5903580808.jpg

正在回答

2 回答

学了操作系统,你应该知道一些进程调度算法吧。先生在调用Thread.sleep(1000)后,表明 在接下来的 1000ms内 先生不参与CPU的竞争,1000ms结束时,cpu并不一定分配给先生,因为windows 的操作系统采用的是 抢占式进程调度算法,进程的优先级 根据等待时间或其它因素 是动态变化的,这时候可能会有 其它进程的优先级比“先生”高,因此先生只能等着。因为 先生 和 女士 的优先级不停变化,所以可能会不规律的被调度。

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消

为什么运行时前几次那么乱呢,一会先生一会女士。不规律

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信