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

  • 纯白微风<alert> 2021-01-30 15:11
    关注

    我看你代码你是想主线程通过调用其它线程的join()方法等其它线程执行完后再执行主线程,那你可以这样写:

    
            for (int i = 0; i < numOfThread; i++) {
                Thread thread = new Thread(new Test1());
                thread.start();
                thread.join();
            }
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

悬赏问题

  • ¥60 Python如何后台操作Vmwake虚拟机键鼠
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容