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

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条回答 默认 最新

相关推荐 更多相似问题