问:代码不能在没有同步方法的情况下工作

时间:2016-07-04 20:41:49

标签: java

我写了一个简单的计数器的应用程序,仅此而已。我的GUI有一个Label和1个按钮用于启动/停止功能。 按钮的EventHandler如下所示:

b_start.setOnAction((ActionEvent e) ->{
        if(!clock.isRunning()){
            clock.setRunning(true);
            b_start.setText("Stop");
            b_start.setStyle("-fx-background-color: red");
        }else{
            clock.setRunning(false);
            b_start.setText("Start");
            b_start.setStyle("-fx-background-color: lightgreen");
        }   
    });

- Clock.java

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package logic;

import java.util.Observable;

/**
 *
 * @author
 */
public class Clock extends Observable implements Runnable {

    private String zeit = "";
    private int sek;
    private boolean isRunning = false;

    public Clock() {

    }

    public void setZeit() {
        zeit = "" + sek;
    }

    public String getZeit() {
        return zeit;
    }

    public void setRunning(boolean running){
        this.isRunning = running;
    }

    public boolean isRunning(){
        return isRunning;
    }

    public int getSek() {
        return sek;
    }

    @Override
    public void run() {
        while (true) {
            System.out.println();
            if (isRunning()) {
                try {
                    sek++;
                    setZeit();
                    System.out.println();
                    this.setChanged();
                    this.notifyObservers();
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    //TODO
                }
            }
        }
    }
}

目前,此代码无效。似乎if() - 子句不可访问但isRunning()返回" true" ..(使用System.out.println测试)

另一种方式:

@Override
public void run() {
    while (true) {
        System.out.println(); //ADDING THIS -> CODE WORKS //DELETE THIS ->    //CODE WONT WORK
        if (isRunning()) {
            try {
                sek++;
                setZeit();
                this.setChanged();
                this.notifyObservers();
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                //TODO
            }
        }
    }
}

为什么我必须使isRunning方法同步//为什么我可以添加一个简单的System.out.println()来使代码执行它所拥有的内容?

0 个答案:

没有答案