public class Maintest
{
public static void main(String args[])
{
ThreadDemo thr = new ThreadDemo();
thr.start();
for(int i=1;i<1000;i++)
{
System.out.println("main: "+i);
}
}
}
class ThreadDemo extends Thread
{
public void run()
{
for(int i=1;i<1000;i++)
{
System.out.println(this.getName()+ ":"+i);
try{
this.sleep(100);
}catch(InterruptedException e){}
}
}
}
{
public static void main(String args[])
{
ThreadDemo thr = new ThreadDemo();
thr.start();
for(int i=1;i<1000;i++)
{
System.out.println("main: "+i);
}
}
}
class ThreadDemo extends Thread
{
public void run()
{
for(int i=1;i<1000;i++)
{
System.out.println(this.getName()+ ":"+i);
try{
this.sleep(100);
}catch(InterruptedException e){}
}
}
}
这个例子很好.
你多运行几遍,正好能发现两个线程的输出结果是如何交叉,混在一起的.每次运行的结果基本是不会一样的,很生动.
CSDN无处不在.
你相信书还是相信网友,自己抉择吧。
自己写例子,的确是进步了,鼓励,但还是建议 勿在浮沙筑高台,基础打好了学这东西就快了.
1.cpu运算速度太快了,你测试的数据对它来说就是瞬间完成,这个瞬间小于轮转时间片
同一代码在不同pc上执行结果都是不一样的
2.时间片切换不是一定精确发生的,有一定几率在里面。
但下面的例子是不严谨的。public class Maintest {
public static void main(String args[]) {
ThreadDemo thr = new ThreadDemo();
thr.start();
for (int i = 1; i < 1000; i++) {
System.out.println("main: " + i);
Thread.yield();
} }
}class ThreadDemo extends Thread {
public void run() {
for (int i = 1; i < 1000; i++) {
System.out.println(this.getName() + ":" + i);
Thread.yield();
}
}
}