读书人

进程有不理解的地方.执行顺序的有关问

发布时间: 2013-07-01 12:33:04 作者: rapoo

进程有不理解的地方.执行顺序的问题


public class Test{

public static void main(String args[]) {
LogOaRentThread2 lt = new LogOaRentThread2();
lt.start();
String ss = "auto mapping";
final String s = ss;
new Thread(){
public void run(){
System.out.println("start");
doMapping(s);
System.out.println("end");
}
}.start();

System.out.println(getBoolean());
}


public static boolean getBoolean(){
return false;
}

public static synchronized void doMapping(String ss){
System.out.println(ss);
}


static class LogOaRentThread2 extends Thread{
public void run (){
System.out.println("LogOaRentThread2 start");
System.out.println("do something");
System.out.println("LogOaRentThread2 end");
}
}

}


Console :

LogOaRentThread2 start
do something
LogOaRentThread2 end
false
start
auto mapping
end
为什么new出来的对象,不是异步的呢?
Java 线程
[解决办法]
你把代码修改一下,你就明白了:
public class Test{

public static void main(String args[]) {
LogOaRentThread2 lt = new LogOaRentThread2();
lt.start();
String ss = "auto mapping";
final String s = ss;
new Thread(){
public void run(){
System.out.println("start");
doMapping(s);
System.out.println("end");
}
}.start();

System.out.println(getBoolean());
}
public static boolean getBoolean(){
return false;
}

public static synchronized void doMapping(String ss){
Thread.currentThread().sleep(5000); // 这块要加trycatch
System.out.println(ss);
}


static class LogOaRentThread2 extends Thread{
public void run (){
System.out.println("LogOaRentThread2 start");
System.out.println("do something");
Thread.currentThread().sleep(5000); // 这块要加trycatch
System.out.println("LogOaRentThread2 end");
}
}
}
其实你看到都是表象,其实都是一样的,只是上面执行很快,没有时间差,你让他们都sleep5秒中就可以看到是不是异步的!
[解决办法]
lz你要弄清个问题:webservice需要返回值不?如果你要返回值的话,可以用Future<>是不能return;如果不需要返回值,就可以直接return。

读书人网 >Java相关

热点推荐