developYan 2021-02-13 21:09 采纳率: 100%
浏览 78
已结题

java 多线程synchronized问题

package com.study.concurrent.demo;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.util.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
class SynchronizedTests {
    @Test
    public void doFor() throws InterruptedException {
        StopWatch sw = new StopWatch();
        CountDownLatch countDownLatch = new CountDownLatch(2);
        sw.start("程序开始执行");
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(()->{
            forValue();
            countDownLatch.countDown();
        });
        executorService.execute(()->{
            forValue();
            countDownLatch.countDown();
        });
        countDownLatch.await();
        executorService.shutdown();
        sw.stop();
        log.info("程序用时,{}",sw.prettyPrint());
    }
    public synchronized void forValue(){
        for (int i = 0; i < 1000000; i++) {
            log.info("输出,{}",i);
        }
    }
}
//运行时间
//1040582528 no synchronized
//942745806 synchronized

各位看官过来看看嘛,synchronized修改的forValue方法,两个线程会顺序执行,第一个线程先输出100万次,第二个线程才开始输入100万。如果forValue方法没被synchronized修饰两个线程是同时执行,顺序交替无序。按理没有synchronized的执行时间应该更短。但是实际测的时间两者相差无几,这是为啥。

  • 写回答

2条回答 默认 最新

  • allway2 2021-02-14 09:27
    关注

    时间都花在log.info("输出,{}",i);上了。把log.info("输出,{}",i);换成非输出等待1秒

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码