What will be the output on compiling/running the following code?
public class MyThread implements Runnable {
String myString = "Yes ";
public void run() {
this.myString = "No ";
}
public static void main(String[] args) {
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}A. compile error
B. prints: yes yes yes yes yes yes and so on
C. prints: no no no no no no no no and so on
D. prints: yes no yes no ye no ye no and so on
E. the output cannot be determined
答案是E,但感觉不对,后来运行了一哈,觉得答案应该是10个no,但运行的结果是10个yes
请教一哈大家啊,这个程序看的不是很懂!!谢谢了
public class MyThread implements Runnable {
String myString = "Yes ";
public void run() {
this.myString = "No ";
}
public static void main(String[] args) {
MyThread t = new MyThread();
new Thread(t).start();
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
}A. compile error
B. prints: yes yes yes yes yes yes and so on
C. prints: no no no no no no no no and so on
D. prints: yes no yes no ye no ye no and so on
E. the output cannot be determined
答案是E,但感觉不对,后来运行了一哈,觉得答案应该是10个no,但运行的结果是10个yes
请教一哈大家啊,这个程序看的不是很懂!!谢谢了
{
MyThread t = new MyThread();
new Thread(t).start();
// Thread.currentThread().sleep(100);
// Thread.currentThread().setPriority(Thread.MAX_PRIORITY) ;
for (int i = 0; i < 10; i++)
System.out.print(t.myString);
}分别使用注释的其中一行再试试其实线程的启动,并不意味着该线程抢占了系统资源立即能够执行,仍然需要操作系统的线程调度机制来调度线程的优先级对于你的方式,10次循环所需的时间太小了,线程根本没有运行,就打印出了t.myString你也可以试试将循环次数放大,可以看到不同的结果
for (int i=0; i < 10; i++)
System.out.print(t.myString);
}
循环中,什么时候myString会变成no是不确定的。
答案应该是E