和线程相关的问题。。。新手求助
public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
Thread.sleep(1);
b = 1000;
System.out.println("b = " + b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("m2.b = "+b);
}
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);
Thread.sleep(15000);
System.out.println(tt.b);
}
}
输出的结果是
m2.b = 2000
2000
b = 1000
1000
不明白为什么m2.b = 2000是第一个输出,已经用了sleep方法让它睡眠了2500毫秒,觉得第一个应该不是它 啊。这意思是比m1方法中先醒吗?求解释啊
[解决办法]
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
Thread.sleep(1);
tt.m2();
System.out.println(tt.b);
Thread.sleep(15000);
System.out.println(tt.b);
b = 1000
m2.b = 2000
2000
2000
Process finished with exit code 0
t.start();//这个是t线程执行
tt.m2();//这个是main线程执行,方法里的sleep(2500),是指main线程睡2.5s