package dxs;
public class TestMain {
/**
* <p>Description: </p>
* <p>Create Time: 2011-5-10 </p>
* @author Semmy
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
Test t=new Test();
Thread a=new Thread(new ThreadA(t));
a.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.methodB();
}
}
class ThreadA implements Runnable{
Test t;
public ThreadA(Test t) {
this.t=t;
}
public void run() {
try {
System.out.println("线程A执行,正在睡眠。。。。");
t.methodA("线程A调用");
System.out.println("线程A执行,完成睡眠。。。。");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Test{
private Integer x=new Integer(10);
public void methodA(String str) throws InterruptedException {
synchronized(x){
System.out.println(str);
System.out.println("x在A中值为:"+x);
Thread.sleep(30000);
x-=1;
System.out.println("x在A中值为:"+x);
}
}
public void methodB() {
synchronized(x){ //aaaaaa
x-=1;
System.out.println("执行B方法");
System.out.println("x在B方法:"+x);
}
}
}
结果:
线程A执行,正在睡眠。。。。
线程A调用
x在A中值为:10
x在A中值为:9
线程A执行,完成睡眠。。。。
执行B方法
x在B方法:8
当 //aaaaaa注释,主线程调用methodB方法中对x对象操作不会被阻塞