jdk1.5 结果如下: --------------------------------------------------- Earth to moon Moon to earth Earth to moon to moon Moon to earth to earth Earth to moon to moon to moon Moon to earth to earth to earth Earth to moon to moon to moon to moon Moon to earth to earth to earth to earth --------------------------------------------------- public class Thread1 implements Runnable { String s1 = "Earth "; String s2 = "Moon "; public void run() { synchronized (s1) { for (int i = 0; i < 2; i++) { s1 = s1.concat("to moon "); System.out.println(s1); s2 = s2.concat("to earth "); System.out.println(s2); } } } public static void main(String[] args) { Thread1 t = new Thread1(); new Thread(t).start(); new Thread(t).start(); } }
concat方法是只返回相加后的值的,并不改两个变母串的值。
public String concat(String str)这是方法说明也就是,这个方法不改变传进来的参数除非你写成 s1 = s1.concat("to moon ");也就是重新赋值
jdk1.4的结果如下Earth to moon Moon to earth Earth to moon to moon Moon to earth to earth Earth to moon to moon to moon Moon to earth to earth to earth Earth to moon to moon to moon to moon Moon to earth to earth to earth to earth
Application 是共用的
Session 是请求独享的
得出的结论应该按照顺序把Earth,moon分别打出来
Earth
Moon
Earth
Moon
Earth
Moon
Earth
Moon
Earth
Moon
Earth
Moon
Earth
Moon
Earth
Moon
请给你说明,解释一下
说明一下?
package test;public class Test
extends Object
implements Runnable {
String s1 = "Earth";
String s2 = "Moon";
public void run() {
synchronized (s1) {
for (int i = 0; i < 2; i++) {
s1.concat("to Moon");
System.out.println(s1);
s2.concat("to Earth");
System.out.println(s2);
}
}
} public static void main(String[] args) {
Test t = new Test();
new Thread(t).start();
new Thread(t).start();
}
}输出结果:
EarthMoonEarthMoonEarthMoonEarthMoon
,然后出因为i=2,出for循环,new Thread(t).start();再执行,此时i为局部变量,i又重新为0,在执行两遍for循环输出,
MoonEarthMoonEarth
s2.concat("to Earth");
这两句话都没有起作用吗?
s2.concat("to Earth");
这两句话都没有起作用吗?同感
s2.concat("to Earth");
===========================
请教各位大哥这是什么意识?
谢了
---------------------------------------------------
Earth to moon
Moon to earth
Earth to moon to moon
Moon to earth to earth
Earth to moon to moon to moon
Moon to earth to earth to earth
Earth to moon to moon to moon to moon
Moon to earth to earth to earth to earth ---------------------------------------------------
public class Thread1 implements Runnable {
String s1 = "Earth "; String s2 = "Moon "; public void run() {
synchronized (s1) {
for (int i = 0; i < 2; i++) {
s1 = s1.concat("to moon ");
System.out.println(s1);
s2 = s2.concat("to earth ");
System.out.println(s2);
}
}
} public static void main(String[] args) {
Thread1 t = new Thread1();
new Thread(t).start();
new Thread(t).start();
}
}
不过在1.4上,好像结果说不通呀!1.5上的结果还可以理解!
至于输出结果 我认为中间部分的moon,earth都是无规律的输出,因为“一个线程以某种顺序启动并不意味着它们将按照该顺序执行”.对于任何一组启动的线程来说,调度程序不保证其顺序.这个面试题和SCJP的题很像啊!
Moon to earth
Earth to moon to moon
Moon to earth to earth
Earth to moon to moon to moon
Moon to earth to earth to earth
Earth to moon to moon to moon to moon
Moon to earth to earth to earth to earth