可以(a == 1&& a == 2&& a == 3)在Java中评估为true? [英] Can (a==1 && a==2 && a==3) evaluate to true in Java?

查看:116
本文介绍了可以(a == 1&& a == 2&& a == 3)在Java中评估为true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道它可以用JavaScript

但是是否可以在Java下面的条件下打印成功消息?

But is it possible to print "Success" message on the condition given below in Java?

if (a==1 && a==2 && a==3) {
    System.out.println("Success");
}

有人建议:

int _a = 1;
int a  = 2;
int a_ = 3;
if (_a == 1 && a == 2 && a_ == 3) {
    System.out.println("Success");
}

但通过这样做我们正在改变实际变量。还有其他方法吗?

But by doing this we are changing the actual variable. Is there any other way?

推荐答案

是的,如果你声明变量<$ c,用多个线程很容易实现这个$ c> a as volatile。

Yes, it's quite easy to achieve this with multiple threads, if you declare variable a as volatile.

一个线程不断地将变量a从1更改为3,另一个线程不断测试 a == 1&& a == 2&& a == 3 。它通常足以在控制台上打印连续的成功流。

One thread constantly changes variable a from 1 to 3, and another thread constantly tests that a == 1 && a == 2 && a == 3. It happens often enough to have a continuous stream of "Success" printed on the console.

(注意如果添加 else {System.out .println(Failure);} 子句,你会发现测试失败的次数远远超过成功次数。)

(Note if you add an else {System.out.println("Failure");} clause, you'll see that the test fails far more often than it succeeds.)

In练习,它也可以在不将 a 声明为易失性的情况下工作,但在我的MacBook上只有21次。如果没有 volatile ,则允许编译器或HotSpot缓存 a 或替换 if 的语句if(false)。最有可能的是,HotSpot会在一段时间后启动并将其编译为汇编指令,这些指令会缓存 a 的值。 使用 volatile ,它会一直打印成功。

In practice, it also works without declaring a as volatile, but only 21 times on my MacBook. Without volatile, the compiler or HotSpot is allowed to cache a or replace the if statement with if (false). Most likely, HotSpot kicks in after a while and compiles it to assembly instructions that do cache the value of a. With volatile, it keeps printing "Success" forever.

public class VolatileRace {
    private volatile int a;

    public void start() {
        new Thread(this::test).start();
        new Thread(this::change).start();
    }

    public void test() {
        while (true) {
            if (a == 1 && a == 2 && a == 3) {
                System.out.println("Success");
            }
        }
    }

    public void change() {
        while (true) {
            for (int i = 1; i < 4; i++) {
                a = i;
            }
        }
    }

    public static void main(String[] args) {
        new VolatileRace().start();
    }
}

这篇关于可以(a == 1&amp;&amp; a == 2&amp;&amp; a == 3)在Java中评估为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆