2.2.6验证同步synchronized(this)代码块是锁定当前对象的

和synchronized方法一样,synchronized(this)代码块也是锁定当前对象的

/**
 * @author wuyoushan
 * @date 2017/3/14.
 */
public class Task {
    public void otherMethod(){
        System.out.println("------------------run--otherMethod");
    }
    public void doLongTimeTask(){
        synchronized (this){
            for (int i = 0; i <1000 ; i++) {
                System.out.println("synchronized threadName="
                +Thread.currentThread().getName()+" i="+(i+1));
            }
        }
    }
}

/**
 * @author wuyoushan
 * @date 2017/4/4.
 */
public class ThreadA extends Thread{

    private Task task;

    public ThreadA(Task task){
        super();
        this.task=task;
    }

    @Override
    public void run() {
        super.run();
        task.doLongTimeTask();
    }
}

/**
 * @author wuyoushan
 * @date 2017/4/4.
 */
public class ThreadB extends Thread{

    private Task task;

    public ThreadB(Task task){
        super();
        this.task=task;
    }

    @Override
    public void run() {
        super.run();
        task.otherMethod();
    }
}

/**
 * @author wuyoushan
 * @date 2017/3/20.
 */
public class Run {
    public static void main(String[] args) throws InterruptedException {
        Task task=new Task();
        ThreadA a=new ThreadA(task);
        a.start();
        Thread.sleep(10);
        ThreadB b=new ThreadB(task);
        b.start();
    }
}

程序运行结果如下:

synchronized threadName=Thread-0 i=212
synchronized threadName=Thread-0 i=213
synchronized threadName=Thread-0 i=214
------------------run--otherMethod
synchronized threadName=Thread-0 i=215
synchronized threadName=Thread-0 i=216
synchronized threadName=Thread-0 i=217

运行的结果为异步的。
修改Task.java如下:

/**
 * @author wuyoushan
 * @date 2017/3/14.
 */
public class Task {
    synchronized public void otherMethod(){
        System.out.println("------------------run--otherMethod");
    }
    public void doLongTimeTask(){
        synchronized (this){
            for (int i = 0; i <1000 ; i++) {
                System.out.println("synchronized threadName="
                +Thread.currentThread().getName()+" i="+(i+1));
            }
        }
    }
}

运行结果如下:

synchronized threadName=Thread-0 i=997
synchronized threadName=Thread-0 i=998
synchronized threadName=Thread-0 i=999
synchronized threadName=Thread-0 i=1000
------------------run--otherMethod
```从上结果可知运行结果是同步的。

> 摘选自 java多线程核心编程技术-2.2.6
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,188评论 19 139
  • 团团跑了。 于是我们又从一个阿姨那里领来两只奶猫。 之前看我朋友给发的视频我一直以为有半个枕头大,谁知良良带回来我...
    轻水阅读 1,427评论 0 0
  • 夏天的早晨,空气凉爽,随同先生一起来到莲池公园。我拉着他直奔莲花盛开的一隅。没有心思去观赏道路两旁的景致,也不曾在...
    欢呼收割一阅读 3,671评论 26 30
  • 毛毛丹阅读 1,306评论 0 0
  • 好久之前和先生闹矛盾,我俩就打起来了(常有的事),先生一拳打到了我的左脸,当时就感觉疼了一下也没在意,第二天发现里...
    慕离烟阅读 1,607评论 0 0

友情链接更多精彩内容