public class SynchronizendTest1 implements Runnable { int b = 10;
public synchronized void m1() throws Exception {
b=1000;
Thread.sleep(3000);
System.out.println("b="+b);
}
public void m2(){
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception{
SynchronizendTest1 st1=new SynchronizendTest1();
Thread t=new Thread(st1);
t.start();
Thread.sleep(1000);
st1.m2();
}
}结果:1000
b=1000。
问题就出现在我把主方法里的Thread.sleep(1000)取消,则结果:10 b=1000.
m1()方法已经是同步方法了。执行到Thread.sleep(3000); b都等于1000了。是这样吗?和主方法里的Thread.sleep(1000)有什么关系 ???
public synchronized void m1() throws Exception {
b=1000;
Thread.sleep(3000);
System.out.println("b="+b);
}
public void m2(){
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception{
SynchronizendTest1 st1=new SynchronizendTest1();
Thread t=new Thread(st1);
t.start();
Thread.sleep(1000);
st1.m2();
}
}结果:1000
b=1000。
问题就出现在我把主方法里的Thread.sleep(1000)取消,则结果:10 b=1000.
m1()方法已经是同步方法了。执行到Thread.sleep(3000); b都等于1000了。是这样吗?和主方法里的Thread.sleep(1000)有什么关系 ???
public class SynchronizedTest1 implements Runnable { volatile int b = 10;
CountDownLatch cd = new CountDownLatch(1);
public void m1() throws Exception {
b = 1000;
cd.countDown();
Thread.sleep(3000);
System.out.println("b=" + b);
} public void m2() {
System.out.println(b);
} @Override
public void run() {
try {
m1();
}
catch(Exception e) {
e.printStackTrace();
}
} public static void main(String args[]) throws Exception {
SynchronizedTest1 st1 = new SynchronizedTest1();
Thread t = new Thread(st1);
t.start();
st1.cd.await();
st1.m2();
}
}