weixin_43253743 2018-09-21 03:20 采纳率: 0%
浏览 769

Java多线程并发问题。

public class Test {
    public static void main(String[] args) throws Exception {
        Executor executor = new Executor();
        new Thread(executor::write).start();
        new Thread(executor::read).start();
        Thread.sleep(500000);
    }

    static class Executor {
        private int MAX_TIMES = 10000;
        private boolean hasValue = false;

        void write() {
            for (int i = 0; i < MAX_TIMES; i++) {
                while (hasValue) {}
                System.out.println("Write, " + i);
                hasValue = true;
            }
        }
        void read() {
            for (int i = 0; i < MAX_TIMES; i++) {
                while (!hasValue) {}
                hasValue = false;
                System.out.println("Read,  " + i);
            }
        }
    }
}

我有这么一段代码,原本目的是两个线程交换执行、write线程执行一次,read线程执行一次,但hasValue并不是volatile类型,所以会发生死锁

我有两个问题:
1. 如果读写都是cache line,那为什么不是刚执行就发生死锁,而是执行一会,大概会交替执行100次左右才死锁。
2. 输出结果很奇怪,为什么不是write 0=> read 0 => write 1=>read 1.......这样下去,实际输出结果是这样的

Write, 0
Write, 1
Read,  0
Read,  1
Write, 2
Read,  2
Write, 3
Write, 4
Read,  3
Read,  4
Write, 5
Write, 6
Read,  5
Read,  6
Write, 7
Write, 8
Read,  7
Read,  8
Write, 9
Write, 10
Read,  9
Read,  10
Write, 11
Write, 12

  • 写回答

6条回答 默认 最新

  • qq_33238448 2018-09-21 03:35
    关注

    如果读写都是cache line,那为什么不是刚执行就发生死锁,而是执行一会,大概会交替执行100次左右才死锁。
    2. 输出结果很奇怪,为什么不是write 0=> read 0 => write 1=>read 1.......这样下去,实际输出结果是这样的

    评论

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办