public class TT implements Runnable
{
int b = 100; //如果m2方法没有加关键字synchronized,就可以在m1锁的同时访问里面的任何东西,
//但是如果加了锁就不可以访问b,必须等m1完成以后.
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println(b);
}
public synchronized void m2() throws Exception{
Thread.sleep(2500);
b = 2000;
}
public void run(){
try{
m1();
}catch(Exception ex){
}
}
public static void main(String[] args) throws Exception
{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}为什么这里是先执行m2方法??
{
int b = 100; //如果m2方法没有加关键字synchronized,就可以在m1锁的同时访问里面的任何东西,
//但是如果加了锁就不可以访问b,必须等m1完成以后.
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println(b);
}
public synchronized void m2() throws Exception{
Thread.sleep(2500);
b = 2000;
}
public void run(){
try{
m1();
}catch(Exception ex){
}
}
public static void main(String[] args) throws Exception
{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}为什么这里是先执行m2方法??
加入了几个输出,来说明一下这个问题。public class TT implements Runnable {
int b = 100; // 如果m2方法没有加关键字synchronized,就可以在m1锁的同时访问里面的任何东西,
// 但是如果加了锁就不可以访问b,必须等m1完成以后.
public synchronized void m1() throws Exception {
b = 1000;
// Thread.sleep(5000);
System.out.println("m1 " + b);
} public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("m2 " + b);
} public void run() {
try {
m1();
} catch (Exception ex) {
}
}
public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start();
tt.m2();
}
}
1. 首先是都m1,m2都使用了sychronized,所以互相不能干扰
2. 执行步骤模拟,其实是这样的:TT tt = new TT(); // 一个主线程的实例
Thread t = new Thread(tt); // 开启一个新的子线程t.start(); // 子线程run,但是这个时候主线程有着优先权(或者有很短的切换时间),而且可以立即执行到tt.m2();
tt.m2(); // 很快执行完毕,接着m1()也顺利执行完毕结果:
主线程 --》 主线程.m2() --》 子线程.m1()========================================================
试验 1:
t.start();
for(int i=0;i<10000000;i++){;} // 让主线程空跑,使得有足够的切换周期到t.m1()上(否则就会被tt.m2()抢得先机)
tt.m2();这样的结果是:t.m1()先执行,tt.m2()后执行,和我们判断一致了!试验2:TT tt = new TT(); // 一个主线程的实例
Thread t = new Thread(tt); // 开启一个新的子线程
Thread.currentThread().setPriority(Thread.MIN_PRIORITY); // 让主线程的优先级别最低
t.setPriority(Thread.MAX_PRIORITY); // 让子线程的优先级最高这样使得子线程有足够的cup时间来执行,进而首先有t.m1(),再有tt.m2()也是和我们的判断一致了!