public class Main { /**
 * @param args
 */
public static void main(String[] args) {
MyThread t = new MyThread();
t.start();

for(int i=0;i<10000;i++)
{
System.out.print("Good");
}
}
}
     
public class MyThread extends Thread {

public void run()
{
for(int i=0;i<10000;i++)
{
System.out.print("Nice");
}
}
}小弟新手请各位大虾指点。上面的代码为何字符串"Good"和"Nice"的交错排列是以单字为单位。而不会交错字符排序呢;例
Go Ni od ce或Goo Ndi ce 等等
我的理解是"Good"和"Nice"是 String型他们都是一个完整字符串   不知有无其他解释

解决方案 »

  1.   

    线程不懂,
    cpu执行程序应该是有一定单位的吧,原子操作?
      

  2.   

    查看源码就能知道为什么
    System.out.print的代码如下,调用write方法。
     public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
        }看下write的源码
    private void write(String s) {
    try {
        synchronized (this) {
    ensureOpen();
    textOut.write(s);
    textOut.flushBuffer();
    charOut.flushBuffer();
    if (autoFlush && (s.indexOf('\n') >= 0))
        out.flush();
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
        }他是同步的,所以不会出现字符交叉
      

  3.   


        
    public class Mythread 
    {  public static void main(String[] args) 

    Thread t1 = new Thread(new a());
    Thread t2 = new Thread(new b());
    t1.start();
    t2.start();

    } class a implements Runnable
    { public void run() 
    {
    // TODO Auto-generated method stub
    for(int i=0;i <100;i++) 

    try
    {
    Thread.sleep(100);
    }catch(Exception e)
    {

    }
    System.out.println("Nice"); 

    }

    }class b implements Runnable
    { public void run() {
    // TODO Auto-generated method stub
    for(int i=0;i <100;i++) 

    try
    {
    Thread.sleep(100);
    }catch(Exception e)
    {

    }
    System.out.println("Good"); 

    }

    }
      

  4.   

    打印一个String类型的字符串是一个原子的操作原子的操作你可以这样理解就是 除了long 和 double之外的所有基本类型之上的‘简单操作’。但是需要提醒一点  如果你光是依赖原子性来保持线程的同步  那么你是很危险的你可以在后面的学习中体会到上面这句话的。