Eglusaxie 2021-01-30 14:36 采纳率: 100%
浏览 36
已采纳

这段java并发代码为啥经常不能正常运行?

//本来我是想比较一下Synchronized和Lock的性能的
public class SynchronizedVSLock {
    static final Lock lock = new ReentrantLock();
    static final int loopTime = 10;
    static final int numOfThread = 6;
    static final Random random = new Random();
    static final Semaphore runningThreadsNum = new Semaphore(numOfThread);
    //这个代码会产生不同的运行结果,但是我不知道原因
    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < numOfThread - 1; i++) {
            new Thread(new Test1()).start();
        }
        new Thread(new Test1()).join();
        runningThreadsNum.acquire(numOfThread);
        long endTime = System.currentTimeMillis();
        System.out.println(endTime - startTime);
    }

    static class Test1 implements Runnable {
        @Override
        public void run() {
            try {
                runningThreadsNum.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException();
            }
            for (int i = 0; i < SynchronizedVSLock.loopTime; i++) {
                SynchronizedVSLock.lock.lock();
                System.out.println(SynchronizedVSLock.random.nextDouble());
                SynchronizedVSLock.lock.unlock();
            }
            runningThreadsNum.release();
        }
    }

    static class Test2 implements Runnable {
        @Override
        public void run() {
            try {
                runningThreadsNum.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException();
            }
            for (int i = 0; i < SynchronizedVSLock.loopTime; i++) {
                synchronized (SynchronizedVSLock.lock) {
                    System.out.println(SynchronizedVSLock.random.nextDouble());
                }
            }
            runningThreadsNum.release();
        }
    }
}
  • 写回答

10条回答

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥30 关于#网络安全#的问题:非对称加密验证
      • ¥20 关于线性代数里施密特正交化和QR分解的疑问
      • ¥15 matlab超类包含解析错误
      • ¥15 python拖拽文件问题
      • ¥15 执行import paddle代码出现错误如何解决?
      • ¥15 hisat2align exited with value 137
      • ¥15 寻找大学生合作开发软件(Delphi)
      • ¥30 AndroidBench&eMMC内存测试速度&Android
      • ¥15 W10 文件共享失败 怎么解决
      • ¥20 b站私信完整导出的方法