代码与老师一样,但运行结果如下:
并不是每个线程分别演出10次,这是什么原因呢?看了下别的答案好像和电脑的CPU核数有关,但还不是很清楚,有人能比较清楚地介绍下吗?
另外,怎么控制才能和老师的输出结果一样呢?
万分感谢!
以下是我的代码
public class Actor extends Thread { public void run() { System.out.println(getName()+"登台演出了!"); int count=0; boolean keepRunning=true; while(keepRunning) { System.out.println(getName()+"登台演出了:"+(++count)); if(count==100) keepRunning=false; if(count%10==0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(getName()+"的演出结束了"); } public static void main(String[] args) { Thread actor= new Actor(); actor.setName("Mr. Thread"); actor.start(); Thread actress = new Thread(new Actress(), "Ms. Runnable"); actress.start(); } } class Actress implements Runnable{ public void run() { System.out.println(Thread.currentThread().getName()+"登台演出了!"); int count=0; boolean keepRunning=true; while(keepRunning) { System.out.println(Thread.currentThread().getName()+"登台演出了:"+(++count)); if(count==100) keepRunning=false; if(count%10==0) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println(Thread.currentThread().getName()+"的演出结束了"); } }
嘿嘿,多运行几次你就会发现,结果不会总是一样的,多核计算机的时间片分配问题
public class Actor extends Thread {
public void run() {
System.out.println(getName()+"登台演出了!");
int count=0;
boolean keepRunning=true;
while(keepRunning) {
System.out.println(getName()+"登台演出了:"+(++count));
if(count==100)
keepRunning=false;
if(count%10==0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(getName()+"的演出结束了");
}
public static void main(String[] args) {
Thread actor= new Actor();
actor.setName("Mr. Thread");
actor.start();
Thread actress = new Thread(new Actress(), "Ms. Runnable");
actress.start();
}
}
class Actress implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName()+"登台演出了!");
int count=0;
boolean keepRunning=true;
while(keepRunning) {
System.out.println(Thread.currentThread().getName()+"登台演出了:"+(++count));
if(count==100)
keepRunning=false;
if(count%10==0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println(Thread.currentThread().getName()+"的演出结束了");
}
}