请帮助解释的多线程的执行顺序问题,先谢谢!synchronized
请解释下以下线程的执行顺序,并且告诉我下,为什么的理解是错误的:
给出两种执行顺序:
1、
thread.start();进去就绪状态---》调用run()方法,走到m1()--->锁定TT,此时b=1000---》进入休眠5秒状态
在sleep过程中,main方法开始执行,TT由于是锁定状态,则main线程不能调用m2()的方法,只有等待thread线程执行完,5秒过后,thread线程执行完,先打印b=1000
然后main线程再调用m2()方法,锁定TT,等待2.5秒以后,设置b的值为200,最后打印tt.b的值为2000
最终显示结果为:
b=1000
2000
2、
thread.start();进去就绪状态---》Main线程执行,调用tt.m2(),TT锁定,m2()方法执行完毕以后才能释放锁,释放锁后thread才能执行m1(),m2休眠2.5秒后,设置b=2000,然后先打印tt.b的值为2000,然后释放锁
然后thread执行m1方法,锁定TT,设置b=1000,等待5秒后,打印b=1000
最终显示结果为:
2000
b=1000
我这边实际的执行结果是
1000
b=1000
1、请解释这是何种逻辑?
2、假如把m2的synchronized关键字去掉,有是一种啥效果?怎么执行的呢?
先谢谢大家!
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;
}
@Override
public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception {
TT tt = new TT();
Thread thread = new Thread(tt);
thread.start();
tt.m2();
System.out.println(tt.b);
}
}
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; } @Override public void run() { try { m1(); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args)throws Exception { TT tt = new TT(); Thread thread = new Thread(tt); thread.start(); tt.m2(); System.out.println(tt.b); } }
public class Test {
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 50; i++) {
T t = new T();
Thread tt = new Thread(t);
tt.start();
t.m2();/*永远先打印m2 因为 tt.start()创建线程需要分配资源等操作,需要耗时,而t.m2()是顺序执行下来的,所以先执行此方法,会锁住t对象实例,线程tt虽然已经启动但任续等待t.m2()方法释放锁。
呵呵楼主多看下多线程方面的书再多做点练习就熟了*/
}
}
}
class T implements Runnable {
public void m1() throws InterruptedException {
synchronized (this) {
// Thread.sleep(2500);
System.out.println("i'm m1");
}
}
public void m2() throws InterruptedException {
synchronized (this) {
// Thread.sleep(5000);
System.out.println("i'm m2");
}
}
public void run() {
try {
m1();
} catch (Exception e) {
}
}
}