public class TT implements Runnable {
int b = 100;
public synchronized void m1() throws Exception{
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);
}
}请问这个程序的执行过程是怎样的;tt.m2()不是得在m1()执行完之后才执行的吗?
怎么打印结果是:
1000
b=1000
int b = 100;
public synchronized void m1() throws Exception{
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);
}
}请问这个程序的执行过程是怎样的;tt.m2()不是得在m1()执行完之后才执行的吗?
怎么打印结果是:
1000
b=1000
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
System.out.println(tt.b);
main方法的时间片还没有用完吧。
所以就先执行了
tt.m2();
System.out.println(tt.b);
则可以让A等待某个条件变为真,然后再执行关键动作。B则可以在执行完某项操作之后
将A等待的那个条件设置为真,然后唤醒A.这样在执行关键操作的时候就可以保证严格的
顺序了。
至于JVM是不是在这个时间点上启动线程,就不是你的事了需要明显等待线程处理的函数,不应该用Runnable接口,而是Callable接口
t.start();而main线程早就启动了的
t.start();
只是启动了线程,
在main线程中,
main线程还没有运行完呢,
所以线程t没有运行
所以tt.m2()它是在主线程中的,它会先运行.
这和你的线程调度有一定的关系.