package thread;public class Demo implements Runnable{
private String name;
public Demo(){
}
public Demo(String name){
this.name=name;
}
public void run(){
for(int i=0;i<20;i++){
System.out.println(name+" 运行 "+i);
}
} public static void main(String[] args) {
// TODO Auto-generated method stub
Demo demo1=new Demo("线程A");
Demo demo2=new Demo("线程B"); Thread thread1=new Thread(demo1);
Thread thread2=new Thread(demo2);
thread1.start();
thread2.start();
}}这里设置循环次数为20,在我的机器上执行,输出总是顺序的(执行了多次,都是顺序的),只有设置的循环次数大时才会看出随机。其中的原因是什么?
而在别人的机器上设置为5都很容易出现随机的输出,从这里可以体现出什么?比如我的机器和别人的机器性能问题?
private String name;
public Demo(){
}
public Demo(String name){
this.name=name;
}
public void run(){
for(int i=0;i<20;i++){
System.out.println(name+" 运行 "+i);
}
} public static void main(String[] args) {
// TODO Auto-generated method stub
Demo demo1=new Demo("线程A");
Demo demo2=new Demo("线程B"); Thread thread1=new Thread(demo1);
Thread thread2=new Thread(demo2);
thread1.start();
thread2.start();
}}这里设置循环次数为20,在我的机器上执行,输出总是顺序的(执行了多次,都是顺序的),只有设置的循环次数大时才会看出随机。其中的原因是什么?
而在别人的机器上设置为5都很容易出现随机的输出,从这里可以体现出什么?比如我的机器和别人的机器性能问题?
要看这个随机性,把循环次数调大,或者sleep1秒就可以看出来了。public class Demo implements Runnable{
private String name;
public Demo(){
}
public Demo(String name){
this.name=name;
}
public void run(){
for(int i=0;i<20;i++){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(name+" 运行 "+i);
}
} public static void main(String[] args) {
// TODO Auto-generated method stub
Demo demo1=new Demo("线程A");
Demo demo2=new Demo("线程B"); Thread thread1=new Thread(demo1);
Thread thread2=new Thread(demo2);
thread1.start();
thread2.start();
}}
CPU是分片(一段时间),这段期间都执行指定线程的逻辑.所以想看随机就要让线程在这次分片中不能结束.