public class TestStopMethod { public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} mt.shutDown(); }}class MyThread extends Thread { private boolean flag = true; public void run() { int i = 0; while (flag) { System.out.println("====" + (i++) + "==="); } } public void shutDown() { flag = false; }}为什么结果的输出不是从1开始的呢?

解决方案 »

  1.   

    http://topic.csdn.net/u/20090731/22/E91059C5-077C-405F-855C-01E5655D9C7F.html这里说的就不错
      

  2.   

    要想从1开始输出 
    要么int i = 1;System.out.println("====" + (i++) + "===");要么int i = 0;System.out.println("====" + (++i) + "===");
      

  3.   

    在TestStopMethod 类主方法线程启动MyThread类的对象mt后的, 睡觉1000 毫秒的时间内,MyThread类的方法run中的while循环体,执行了6000 余次循环, 故在停止前, 我的机器能打印到====7286===。若在 MyThread类run方法中的循环体中,也加上睡觉1000毫秒的限制,那只能打印到 ====1====。
    public class TestStopMethod { public static void main(String[] args) { 
    MyThread mt = new MyThread(); 
    mt.start(); 
    try { 
    Thread.sleep(1000); 
    } catch (InterruptedException e) { 
    e.printStackTrace(); 

    mt.shutDown(); 

    } class MyThread extends Thread { 
    private boolean flag = true; 
    public void run() { 
    int i = 0; 
    while (flag) { 
    System.out.println("====" + (i++) + "==="); 
      try {  //加上睡觉1000毫米的操作
    Thread.sleep(1000); 
    } catch (InterruptedException e) { 
    e.printStackTrace(); 
    }

    } public void shutDown() { 
    flag = false; 

    }我的机器输出为:
    ====0===
    ====1===
      

  4.   

    一楼正解,建议楼主看看java运算符相关资料
      

  5.   

    回复:tongj2me   那每次循环不是都应该有输出吗?
      

  6.   

    LZ
    (i++)去掉括号就是你要求的了。
      

  7.   

    因为 mt.shutDown(); 
    注释掉,每次都会循环。
      

  8.   

    一楼正解,i++ 是先赋值再++++i 是先++再赋值int i = 1;
    System.out.println(i++); //输出结果: 1;
    System.out.println(++i); //输出结果: 2;
      

  9.   

    更正:
       
        int i = 1;
    System.out.println(i++); //输出结果:1
    System.out.println(++i); //输出结果:3
    //原因是i++了一次.所以i在第二次是2.因为它++了.所以在++i的时候会在2的基础上先加在赋值
    //更正Code:
    int i = 1;
    int j = 1;
    System.out.println(i++); //输出结果:1
    System.out.println(++j); //输出结果:2