public class Example8_3{
    public static void main(String args[ ]){
        Left left=new Left();
        Right right=new Right();
        left.start();
        right.start();
        while(true){
          if(left.n==8||right.n==8)
             System.exit(0);
        }  
    }
}
class Left extends Thread{
    int n=0;
    public void run(){
        while(true){
            n++;
            System.out.printf("\n%s","我在左面写字");
            try {  sleep((int)(Math.random()*100)+100);
            }
            catch(InterruptedException e) {}
        }
    }
}
class Right extends Thread{
    int n=0;
    public void run(){
        while(true){
            n++;
            System.out.printf("\n%40s","我在右面写字");
            try {  sleep((int)(Math.random()*100)+100);
            }
            catch(InterruptedException e) {}
        }
    }
}
这个程序的执行结果,
我在左面写字
                                  我在右面写字
我在左面写字
                                  我在右面写字
我在左面写字
                                  我在右面写字
我在左面写字
                                  我在右面写字
我在左面写字
                                  我在右面写字
                                  我在右面写字
我在左面写字
我在左面写字
                                  我在右面写字
请问各位高手,为什么会出现左右这样的显示结果呢??

解决方案 »

  1.   

    两个线程执行,分别打印左边右边,线程的执行是随机的,再加上线程里的sleep时间也是随机的,所以没有什么输出顺序,就是随机的交错输出
      

  2.   

    System.out.printf("\n%40s","我在右面写字");意思:输出换行 且占40列的位置 所以从第40个位置开始输出 我在右面写字System.out.printf("\n%s","我在左面写字");只换行   输出从最左边开始输出
      

  3.   

    原来LZ是在说打印格式啊
    \n 表示换行
    %s 表示打印一个字符串(缺省格式,左对齐)
    %40s 表示打印一个固定长度(40)的字符串,当字符串不满足长度时,左边补空格(相当于右对齐)
    %-40s 和%40s相反,当字符串不满足长度时,右边补空格 (相当于左对齐)
      

  4.   

      System.out.printf("\n%s","我在左面写字");
      System.out.printf("\n%40s","我在右面写字");
    仔细琢磨这两句话就行了
      

  5.   

    楼主看到了sleep((int)(Math.random()*100)+100) 这个语句了吗,也就是两个线程在运行的过程当中,会sleep,如此的话另外一个线程就可以进行打印相关的信息了。。
      

  6.   

    System.out.printf("\n%s","我在左面写字");
      System.out.printf("\n%40s","我在右面写字");
    仔细琢磨这两句话就行了