public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
这个运行结果是多少??我认为要么是b == 1000 ,1000 ; 要么是2000 , b == 1000 不知道这个结果对不对 各位帮看一下,谢了
这是怎么样回事啊 对这个结果很不能理解
public class Test {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println("main():"+tt.b);
}
}
class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
//Thread.sleep(2000);
System.out.println("m1");
b = 1000;
Thread.sleep(5000);
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
System.out.println("m2");
Thread.sleep(2500);
b = 2000;
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
}
改为这样,你就可以看清楚到底是谁获得cpu,我两个结果都出现过
1、m1方法先运行,结果为b=1000 2000
2、m2方法先运行,System.out.print(tt.b)时,b=1000已经执行,结果为1000 b=1000
3、m2方法先运行,System.out.print(tt.b)时,b=1000未执行,结果为2000 b=1000
不是线程调动了,而是普通的函数调用了,这是你本来的意图吗??
不过我运行了后发现m2一直比m1先运行
System.out.println(tt.b); 这条语句有时出1000,有时出2000
http://topic.csdn.net/u/20081123/08/92eafee3-a0e0-4015-b639-76665a64e455.html
有个回答的很好的 他说了为什么会有两种情况
t.start();
tt.m2();
在说了m1()和m2() 都有加synchronized,应该是m1()没有执行完就不会在执行m2()
m2为什么会先执行呢?