Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 循环不';在没有打印语句的情况下,看不到其他线程更改的值_Java_Multithreading_Synchronization_Busy Waiting - Fatal编程技术网

Java 循环不';在没有打印语句的情况下,看不到其他线程更改的值

Java 循环不';在没有打印语句的情况下,看不到其他线程更改的值,java,multithreading,synchronization,busy-waiting,Java,Multithreading,Synchronization,Busy Waiting,在我的代码中,我有一个循环,它等待某个状态从另一个线程更改。另一个线程工作,但我的循环从未看到更改的值它将永远等待。然而,当我在循环中放入System.out.println语句时,它突然工作了!为什么? 以下是我的代码示例: class MyHouse { boolean pizzaArrived = false; void eatPizza() { while (pizzaArrived == false) { //System.o

在我的代码中,我有一个循环,它等待某个状态从另一个线程更改。另一个线程工作,但我的循环从未看到更改的值它将永远等待。然而,当我在循环中放入
System.out.println
语句时,它突然工作了!为什么?


以下是我的代码示例:

class MyHouse {
    boolean pizzaArrived = false;

    void eatPizza() {
        while (pizzaArrived == false) {
            //System.out.println("waiting");
        }

        System.out.println("That was delicious!");
    }

    void deliverPizza() {
        pizzaArrived = true;
    }
}

当While循环运行时,我从另一个线程调用
deliverPizza()
,以设置
pizzarrived
变量。但是循环只有在我取消注释
System.out.println(“waiting”)时才起作用语句。发生了什么?

允许JVM假设其他线程在循环期间不更改
变量。换言之,它可以将
pizzarrived==false
测试提升到循环之外,从而优化:

while (pizzaArrived == false) {}
为此:

if (pizzaArrived == false) while (true) {}
这是一个无限循环

要确保一个线程所做的更改对其他线程可见,必须始终在线程之间添加一些同步。最简单的方法是将共享变量
设置为volatile

volatile boolean pizzaArrived = false;
将变量设置为volatile可保证不同线程将看到彼此对其所做更改的效果。这可以防止JVM缓存
pizza
的值或将测试提升到循环之外。相反,它必须每次读取实变量的值

(更正式地说,
volatile
在变量访问之间创建了一个发生在之前的关系。这意味着在发送比萨饼之前,接收比萨饼的线程也可以看到比萨饼,即使这些其他更改不是对
volatile
变量的。)

主要用于实现互斥(防止两件事情同时发生),但它们也具有与
volatile
相同的副作用。在读写变量时使用它们是使更改对其他线程可见的另一种方法:

class MyHouse {
    boolean pizzaArrived = false;

    void eatPizza() {
        while (getPizzaArrived() == false) {}
        System.out.println("That was delicious!");
    }

    synchronized boolean getPizzaArrived() {
        return pizzaArrived;
    }

    synchronized void deliverPizza() {
        pizzaArrived = true;
    }
}

打印语句的效果
System.out
是一个
PrintStream
对象。
PrintStream
的方法同步如下:

public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
}
同步可防止在循环期间缓存
pizza
。严格来说,两个线程必须在同一个对象上同步,以确保变量的更改可见。(例如,在设置
pizzaarized
之后调用
println
,并在读取
pizzaarized
之前再次调用它是正确的。)如果只有一个线程在特定对象上同步,JVM可以忽略它。实际上,JVM不够聪明,无法证明其他线程在设置
pizza
后不会调用
println
,因此它假设其他线程可能会调用。因此,如果调用
System.out.println
,它将无法在循环期间缓存变量。这就是为什么这样的循环在有print语句时可以工作,尽管这不是一个正确的修复方法

使用
System.out
并不是造成这种效果的唯一方法,但这是人们在调试循环为何不工作时最常发现的方法


更大的问题
while(pizzaarived==false){}
是一个繁忙的等待循环。那太糟糕了!在等待时,它占用CPU,这会减慢其他应用程序的速度,并增加系统的功耗、温度和风扇速度。理想情况下,我们希望循环线程在等待时休眠,这样它就不会占用CPU

以下是一些方法:

使用等待/通知 低级解决方案是:

在这个版本的代码中,循环线程调用,这使线程处于睡眠状态。它在睡眠时不会使用任何CPU周期。在第二个线程设置变量后,它调用以唤醒正在等待该对象的任何/所有线程。这就像让披萨店的伙计按门铃,这样你就可以在等待的时候坐下休息,而不是尴尬地站在门口

在对对象调用wait/notify时,必须持有该对象的同步锁,这就是上面的代码所做的。只要两个线程使用相同的对象,您就可以使用任何您喜欢的对象:这里我使用了
this
(MyHouse的实例)。通常,两个线程不能同时进入同一对象的同步块(这是同步的一部分),但它在这里工作,因为线程在
wait()
方法中时会临时释放同步锁

阻塞队列 用于实现生产者-消费者队列。“消费者”从队列的前面拿走物品,“生产者”将物品推到后面。例如:

class MyHouse {
    final BlockingQueue<Object> queue = new LinkedBlockingQueue<>();

    void eatFood() throws InterruptedException {
        // take next item from the queue (sleeps while waiting)
        Object food = queue.take();
        // and do something with it
        System.out.println("Eating: " + food);
    }

    void deliverPizza() throws InterruptedException {
        // in producer threads, we push items on to the queue.
        // if there is space in the queue we can return immediately;
        // the consumer thread(s) will get to it later
        queue.put("A delicious pizza");
    }
}
有关详细信息,请参阅和的文档

事件处理 在等待用户单击UI中的某些内容时进行循环是错误的。相反,请使用UI工具包的事件处理功能,例如:

JLabel label = new JLabel();
JButton button = new JButton("Click me");
button.addActionListener((ActionEvent e) -> {
    // This event listener is run when the button is clicked.
    // We don't need to loop while waiting.
    label.setText("Button was clicked");
});
由于事件处理程序在事件分派线程上运行,因此在事件处理程序中执行长时间工作会阻止与UI的其他交互,直到工作完成。可以在新线程上启动慢速操作,也可以使用上述技术之一(等待/通知、
BlockingQueue
Executor
)将其分派给等待的线程。您还可以使用专门为此设计的,并自动提供后台工作线程的:

JLabel label = new JLabel();
JButton button = new JButton("Calculate answer");

// Add a click listener for the button
button.addActionListener((ActionEvent e) -> {

    // Defines MyWorker as a SwingWorker whose result type is String:
    class MyWorker extends SwingWorker<String,Void> {
        @Override
        public String doInBackground() throws Exception {
            // This method is called on a background thread.
            // You can do long work here without blocking the UI.
            // This is just an example:
            Thread.sleep(5000);
            return "Answer is 42";
        }

        @Override
        protected void done() {
            // This method is called on the Swing thread once the work is done
            String result;
            try {
                result = get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            label.setText(result); // will display "Answer is 42"
        }
    }

    // Start the worker
    new MyWorker().execute();
});
每个
java.util.Timer
都有自己的后台线程,用于执行其计划的
TimerTask
s。当然,线程在任务之间休眠,因此它不会占用CPU

在Swing代码中,还有一个类似的,但它在Swing线程上执行侦听器,因此您可以安全地与Swing组件交互,而无需手动切换线程:

JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(1000, (ActionEvent e) -> {
    frame.setTitle(String.valueOf(System.currentTimeMillis()));
});
timer.setRepeats(true);
timer.start();
frame.setVisible(true);
另一种方式
JLabel label = new JLabel();
JButton button = new JButton("Calculate answer");

// Add a click listener for the button
button.addActionListener((ActionEvent e) -> {

    // Defines MyWorker as a SwingWorker whose result type is String:
    class MyWorker extends SwingWorker<String,Void> {
        @Override
        public String doInBackground() throws Exception {
            // This method is called on a background thread.
            // You can do long work here without blocking the UI.
            // This is just an example:
            Thread.sleep(5000);
            return "Answer is 42";
        }

        @Override
        protected void done() {
            // This method is called on the Swing thread once the work is done
            String result;
            try {
                result = get();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            label.setText(result); // will display "Answer is 42"
        }
    }

    // Start the worker
    new MyWorker().execute();
});
Timer timer = new Timer();
TimerTask task = new TimerTask() {
    @Override
    public void run() {
        System.out.println(System.currentTimeMillis());
    }
};
timer.scheduleAtFixedRate(task, 0, 1000);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Timer timer = new Timer(1000, (ActionEvent e) -> {
    frame.setTitle(String.valueOf(System.currentTimeMillis()));
});
timer.setRepeats(true);
timer.start();
frame.setVisible(true);