下面的类在运行的时候,m1只睡了500,而m2睡了9500,在运行的时候确是m2先输出...package lang.thread.demo;
public class NewThread implements Runnable{
int b = 100;
public synchronized void m1(){
b = 1000 ;
System.out.println("m1 : " + b);
try{
Thread.sleep(500);
}catch(InterruptedException ex){
ex.printStackTrace();
}
System.out.println("b=" + b);
}
public synchronized void m2(){
try{
Thread.currentThread().sleep(9500);
}catch(InterruptedException ex){
ex.printStackTrace();
}
b = 2000 ;
System.out.println("m2:" + b);
}
public void run(){
m1();
}
public static void main(String[] args){
NewThread nt = new NewThread();
Thread thread = new Thread(nt);
thread.start();
nt.m2();
System.out.println(nt.b);
}
}结果:m2:2000
2000
m1 : 1000
b=1000
你把synchronized去掉后就可以得到预期结果了
nt.m2();你认为这2个语句到底谁的速度快一些
1 线程启动,然后运行到run的方法,拿到同步锁
2 当前main,继续运行也拿到了同步锁。我永远支持2,呵呵!