class A implements Runnable
{
public void run()
{
}
}
public class Object12
{
public static void main(String args[]) throws Exception
{
Thread p = new Thread(new A(),"Pkj"); p.start();

p.sleep(1000);//问题1:为什么将这句话注释掉后,输出结果就不一样了 p.interrupt();//问题2:还有就是将这该语句放到p.sleep(1000)之前执行有什么区别? System.out.println(p.isInterrupted());
System.out.println(p.isAlive());
}
}问题3:p.sleep(1000)是指线程p睡眠吧,但为什么main中的语句也进入睡眠状态       (表达的不是很好。。换句话说:假如让线程p睡眠10秒,为什么p.sleep(10000)后面的一些输出语句         也要在10秒后输出?main也是一个线程,为什么它也进入了睡眠)

解决方案 »

  1.   

    sleep是个静态方法,所有它指的总是当前的线程
    interrupt也是个静态方法
      

  2.   

    在A的run方法中加入        
         System.out.println("exiting run");
        能加深你的理解。
    问题1: p.sleep(1000);其实这个sleep是Thread的静态方法,在指定的毫秒数内让当前正在执行的线程休眠(暂停执行)
    由于p线程里面没有执行东西,所以很快就结束了。这里睡眠的其实是main线程。 
    既然p结束了,当然就没有被阻塞,打印:
    exiting run
    false
    false如果注释掉p.sleep(1000);由于调用了p.interrupt();这时p线程当然存在,打印
    true
    true
    exiting run问题2  
    注释sleep的话,打印:
    true
    true
    exiting run
    这个好理解。p线程被阻塞了。当然还存活。最后又被调度了。所以有exiting run打印不注释sleep的话打印:
    exiting run
    false
    false
    也是main线程睡眠
      

  3.   

    interrupt也是个静态方法?
    这个太牛叉了吧。当然不是。
      

  4.   

    没注意,interrupted是静态的,interrupt不是
      

  5.   

    那下面的这段代码中:
    class A implements Runnable
    {
    public void run() throws Exception
    {
    for(int i=0; i<10; i++)
    {
    try
    {
    Thread.sleep(1000);
    }
    catch (Exception e)
    {
    System.out.println(e);
    }
    System.out.println(Thread.currentThread().getName() + "is running");
    }
    }
    }
    public class Object9
    {
    public static void main(String args[])throws Exception
    {
    Thread p1 = new Thread(new A(),"1~~~");

    p1.start(); p.sleep(10000); //那此处为什么睡眠的是main,而且将该语句换成 Thread.sleep(10000)                                //也一样,这2个语句有什么区别么?  for(int i=0; i<10; i++)
    System.out.println("@@@@@@@@");
    }
    }
      

  6.   

    把上面的 p.sleep(10000) 改成 p1.sleep(10000);