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型他们都是一个完整字符串 不知有无其他解释
* @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型他们都是一个完整字符串 不知有无其他解释
cpu执行程序应该是有一定单位的吧,原子操作?
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;
}
}他是同步的,所以不会出现字符交叉
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");
}
}
}