以下程序为什么一定能确定是执行m1先??public class DeadLock1 implements Runnable {
int b=100;
public synchronized void m1() throws Exception {
b=1000;
Thread.sleep(50);
System.out.println("b="+b);
} public synchronized void m2() throws Exception {
Thread.sleep(80);
b=2000;
}
public void run() {
try {m1();}
catch(Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
DeadLock1 tt=new DeadLock1();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}threadexception
int b=100;
public synchronized void m1() throws Exception {
b=1000;
Thread.sleep(50);
System.out.println("b="+b);
} public synchronized void m2() throws Exception {
Thread.sleep(80);
b=2000;
}
public void run() {
try {m1();}
catch(Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
DeadLock1 tt=new DeadLock1();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}threadexception
你的这种情况只是输出语句的位置让楼主产生了误解而已
不信的话楼主可以分别在两个方法中的sleep语句前面
加上一句输出语句,看看谁先执行!个人觉得一般情况下m2是先于m1执行的:
t线程启动后,要等待虚拟机的调度,而m2()就在主线程里运行,(已经在运行了)
少所以m1先醒过来
跟sleep多久有关吗??加了锁我就可以睡一辈子了
"加了锁睡一辈子" 那还要球个锁啊,"锁"只是用于我们在多线程下
对临界资源的访问控制.
一般是主线程的m2先执行
至于原因:t线程启动后,要等待虚拟机的调度,而m2()就在主线程里运行,(已经在运行了)
仅作参考
就是问是不是一定啦,多次运行证明肯定是m2先 根据你的原因: 把synchronized去掉,就很随机了 t线程一样有好多机会先运行PS:想请教各位哥们的是:上面代码一定是先执行m2吗??