重排序,12-6这一节代码

来源:12-6 重排序1

IBelieveYY

2019-12-27

第12-6这一节,我的idea在编辑代码的时候,CountDownLatch latch = new CountDownLatch(1); 这行代码,必须要加final关键字,才不报错。提示:Variable ‘latch’ is accessed from within inner class, needs to be declared final。

为什么,看视频,老师好像没有加这个,都能正常运行呢。
![图片描述](http://img1.sycdn.imooc.com/szimg/5e0603b50859b8ec12161312.jpg
图片描述

完整代码:

package concurrencyknowledge.jmm;

import java.util.concurrent.CountDownLatch;

/**
 * @Created by jasyu 2019/12/26
 *
 * 1. a=1;x=b(0);b=1;y=a(1)         x=0,y=1
 * 2. b=1;y=a(0);a=1;x=b(1)         x=1,y=0
 * 3. b=1;a=1;x=b(1);y=a(1)         x=1,y=1
 */
public class OutOfOrderException {
    private static int a = 0, x = 0;
    private static int b = 0, y = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ;) {
            i++;
            a = 0;
            x = 0;
            b = 0;
            y = 0;

            final CountDownLatch latch = new CountDownLatch(1);
            Thread one = new Thread(new Runnable() {
                public void run() {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    a = 1;
                    x = b;
                }
            });

            Thread two = new Thread(new Runnable() {
                public void run() {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    b = 1;
                    y = a;
                }
            });

            one.start();
            two.start();
            latch.countDown();
            one.join();
            two.join();

            String result = "[run " + i + "times] x = " + x + ", y = " + y;
            if (x == 1 && y == 1) {
                System.out.println(result);
                break;
            } else {
                System.out.println(result);
            }
        }
    }
}
写回答

3回答

悟空

2019-12-27

看下这里:

//img.mukewang.com/szimg/5e0622eb09bbb4f511880504.jpg

0
2
悟空
回复
IBelieveYY
不客气。最后是怎么解决的呢?说出来和大家分享一下。
2019-12-28
共2条回复

悟空

2019-12-27

你版本是java8吗

0
2
悟空
回复
IBelieveYY
不用加final是1.8的新特性,参考: https://docs.oracle.com/javase/tutorial/java/javaOO/localclasses.html#accessing-members-of-an-enclosing-class https://blog.csdn.net/u014285517/article/details/46945453 https://blog.csdn.net/yidou120/article/details/83998431
2019-12-27
共2条回复

悟空

2019-12-27

你对比一下我的代码,看看是不是哪里不一样。

//img.mukewang.com/szimg/5e05ae36090a624913222102.jpg


0
5
悟空
回复
IBelieveYY
是的,我复制你的代码在我的IDE跑,不加final也可以
2019-12-27
共5条回复

线程八大核心+Java并发原理及企业级并发解决方案

完整的并发知识网络+丰富的工作内容分享+50余道并发高频面试题

2512 学习 · 939 问题

查看课程