多线程
先看一段代码
public class TestSync2 implements Runnable {
int b=100;
public int getB() {
return b;
}
@Override
public void run() {
try {
m1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized void m1() throws InterruptedException {
System.out.println("m1");
b=1000;
Thread.sleep(500);
b=666;
System.out.println("b="+b);
}
synchronized void m2() throws InterruptedException {
System.out.println("m2");
Thread.sleep(250);
b=2000;
}
public static void main(String[] args) throws InterruptedException {
TestSync2 tt=new TestSync2();
Thread t = new Thread(tt);
t.start();
tt.m2();
// Thread.sleep(2000);
System.out.println("main thread b="+tt.getB());
}
运行结果为
或者
请注意变量i没加volatile,读出来的都是最新的。这是因为当一个类中有方法synchronized修饰的时候,里面涉及的变量无需加