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) {}
}
}
}
这个程序的执行结果,
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在右面写字
我在左面写字
我在左面写字
我在右面写字
请问各位高手,为什么会出现左右这样的显示结果呢??
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) {}
}
}
}
这个程序的执行结果,
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在左面写字
我在右面写字
我在右面写字
我在左面写字
我在左面写字
我在右面写字
请问各位高手,为什么会出现左右这样的显示结果呢??
\n 表示换行
%s 表示打印一个字符串(缺省格式,左对齐)
%40s 表示打印一个固定长度(40)的字符串,当字符串不满足长度时,左边补空格(相当于右对齐)
%-40s 和%40s相反,当字符串不满足长度时,右边补空格 (相当于左对齐)
System.out.printf("\n%40s","我在右面写字");
仔细琢磨这两句话就行了
System.out.printf("\n%40s","我在右面写字");
仔细琢磨这两句话就行了