public class TT implements Runnable{
int b = 100;
public void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b="+b);
}
public void m2() throws Exception{
b = 2000;
Thread.sleep(500);
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
}
}
public static void main(String args[]) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}执行结果是多少?
为什么是这个结果,我百思不得其解!
int b = 100;
public void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b="+b);
}
public void m2() throws Exception{
b = 2000;
Thread.sleep(500);
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
}
}
public static void main(String args[]) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}执行结果是多少?
为什么是这个结果,我百思不得其解!
public class TT implements Runnable{
int b = 100;
public void m1() throws Exception{
b = 1000;
Thread.sleep(500);
System.out.println("b="+b);
}
public void m2() throws Exception{
b = 2000;
Thread.sleep(3000);
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
}
}
public static void main(String args[]) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();tt.m2();
}
}
这个答案又是多少呢?
程序里有两个线程,本身的main方法的线程main,然后里边还有一个线程t首先是执行main线程,虽然对t进行了start调用,它当前的时间还没有用完,接着马上进入tt对象的方法m2,此时main线程锁住了对象tt,线程t再启动的时候,它无法进入m1()方法.只能是等m2方法执行完,才能执行m1方法public static void main(String args[]) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();//在此处加一定延迟的话,就会是t线程先执行了
tt.m2();
}
}
1.主线程m2()执行,b=2000,休眠200ms
2.线程t执行,b=1000,休眠5s
3.主线程m2()继续执行,打印b,b为1000
4.线程t2继续执行打印b=1000结果:1000
b=1000第二题类似
public class TT implements Runnable{
int b = 100;public void m1() throws Exception{
b = 1000;
System.out.println("m1");
Thread.sleep(5000);
System.out.println("b="+b);
}public void m2() throws Exception{
b = 2000;
System.out.println("m2");
Thread.sleep(500);
System.out.println(b);
}public void run(){
try{
m1();
}catch(Exception e){}}
public static void main(String args[]) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);t.start();
tt.m2();
}
}
得出的输出是:
m2
m1
1000
b=1000
得出这样的结果,我想就不必要多做解释了吧。所以要善于调试。
1 m2->b=2000 m2休眠.main()函数走完;
2 m1->b=1000 执行m2的输出;m1休眠.m2走完
3 执行m1的方法