//USEthreads.javaclass MyThread implements Runnable
{
int count;
Thread thrd;
MyThread(String name)
{
thrd =  new Thread(this,name);
count = 0;
thrd.start();
}
public void run()
{
System.out.println(thrd.getName()+"starting");
try
{
do
{
Thread.sleep(500);
System.out.println("In"+thrd.getName()+",count is"+count);
count++;
}
while (count < 10);
}
catch (InterruptedException exc)
{
System.out.println(thrd.getName()+"interrupted");
}
System.out.println(thrd.getName()+"terminzting.");
}
}
class USEthreads 
{
public static void main(String[] args) 
{
System.out.println("Main thread starting.");
MyThread mt = new MyThread("chile#1");

do
{
System.out.println(".");
try
{
Thread.sleep(100);
}
catch (InterruptedException exc)
{
System.out.println("Main thread interrupted.");
}
}
while (mt.count!=10);
System.out.println("Main thread ending");
}
}运行结果:
Main thread starting.
.
chile#1starting
.
.
.
.
Inchile#1,count is0
.
.
.
.
.
Inchile#1,count is1
.
.
.
.
.
Inchile#1,count is2
.
.
.
.
.
Inchile#1,count is3
.
.
.
.
.
Inchile#1,count is4
.
.
.
.
.
Inchile#1,count is5
.
.
.
.
.
Inchile#1,count is6
.
.
.
.
.
Inchile#1,count is7
.
.
.
.
.
Inchile#1,count is8
.
.
.
.
.
Inchile#1,count is9
chile#1terminzting.
Main thread ending不解啊,哪位帮忙解释一下
按我的理解分析,每串英文字符之间应该都是五个点的间隔啊,怎么有的有四个,有的是五个点简隔?而且还没有规律.

解决方案 »

  1.   

    在sleep 时间间隔期满后,线程不一定立即恢复执行。这是因为在那个时刻,其它线程可能正在运行而且没有被调度为放弃执行,除非“醒来”的线程具有更高的优先级
      

  2.   

    sleep你可以看看他的API说明,他有些须差异,时间不是刚好等于被唤醒,唤醒后CPU处理分配给哪个线程由操作系统调度算法决定的,而且,System.out.print方法本身是同步的,在两个线程都输出的时候,要被同步处理
      

  3.   

    MyThread mt = new MyThread("chile#1");
    在上面的语句执行完毕后, main 和 MyThread 已经处于并行状态.sleep也只是让USEthreads休眠, 因此两者的执行速度是不可预期的.所以上面的结果很正常.
      

  4.   

    速度不可以用sleep中的参数来度量的