黑马程序员技术交流社区

标题: 同步代码块的锁 [打印本页]

作者: izwj    时间: 2012-3-29 13:43
标题: 同步代码块的锁
public class ThreadTest implements Runnable {
    int number = 10;
        Object o=new Object();
    public void firstMethod() throws Exception {
        synchronized (this) {
            number += 100;
            System.out.println(number);
        }
    }

    public void secondMethod() throws Exception {
        synchronized (this) {
            //Thread.sleep(2000);
            this.wait(2000);
            number *= 200;
        }
    }

     public void run() {
        try {
            firstMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        ThreadTest threadTest = new ThreadTest();
        Thread thread = new Thread(threadTest);
        thread.start();
        threadTest.secondMethod();
    }
}
两个同步代码块的this是同一个锁吗?
作者: 罗杰    时间: 2012-3-29 13:53
是的,this就是指向这个类本身,这两个方法都在同一个类中。
并且想要同步就是需要给AB设置同一个锁来保证当A同步代码块执行时B代码不能执行




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2