我有2个嵌套的while循环,如果我停止内循环,外部停止检查内部是否运行。我有启动和停止计时器的方法,但是如果我停止计时器然后重新启动它(将布尔值设置为true),计时器就不会启动。如果我在外部循环中执行一些操作,如System.out.println(“test”),而内部暂停,它可以正常工作。
@Override
protected synchronized Void call() throws Exception {
while(true){
System.out.println();
while(play){
System.out.println(play);
secondCounter++;
seconds++;
if(seconds>59){
secondCounter=0;
seconds=0;
minutes++;
}
if(minutes>59){
minutes=0;
hours++;
}
System.out.println("Task sekunden: "+seconds);
setTime();
Thread.sleep(1000);
}
}
}
这是完整的课程:
public class TimerTask extends Task<Void>{
private Label timer;
private boolean play=false;
private int secondCounter;
private int seconds;
private int minutes;
private int hours;
public TimerTask(Label timer){
this.timer=timer;
}
@Override
protected synchronized Void call() throws Exception {
while(true){
while(play){
System.out.println(play);
secondCounter++;
seconds++;
if(seconds>59){
secondCounter=0;
seconds=0;
minutes++;
}
if(minutes>59){
minutes=0;
hours++;
}
System.out.println("Task sekunden: "+seconds);
setTime();
Thread.sleep(1000);
}
}
}
public int getMinutes(){
int time;
time=minutes + (hours*60);
if(seconds>30){
time++;
}
return time;
}
public void test(){
String secondsTime;
String minutesTime;
String hoursTime;
if(seconds<10){
secondsTime="0"+seconds;
}else{
secondsTime=String.valueOf(seconds);
}
if(minutes<10){
minutesTime="0"+minutes;
}else{
minutesTime=String.valueOf(minutes);
}
if(hours<10){
hoursTime="0"+hours;
}else{
hoursTime=String.valueOf(hours);
}
System.out.println(hoursTime+":"+minutesTime+":"+secondsTime);
}
public void setTime(){
String secondsTime;
String minutesTime;
String hoursTime;
if(seconds<10){
secondsTime="0"+seconds;
}else{
secondsTime=String.valueOf(seconds);
}
if(minutes<10){
minutesTime="0"+minutes;
}else{
minutesTime=String.valueOf(minutes);
}
if(hours<10){
hoursTime="0"+hours;
}else{
hoursTime=String.valueOf(hours);
}
Platform.runLater(() -> {timer.setText(hoursTime+":"+minutesTime+":"+secondsTime);});
}
public void stop(){
this.play=false;
System.out.println("Stop: "+play);
}
public void start(){
this.play=true;
System.out.println("Start: "+play);
}
public void reset(){
this.play=false;
secondCounter=0;
seconds=0;
minutes=0;
hours=0;
timer.setText("00:00:00");
System.out.println("Reset: "+play);
}
}
答案 0 :(得分:0)
play
,但不是易失性的。因此,您无法保证其可见性。一个线程可以将其设置为true,另一个线程永远将其视为false。
其余代码根本不是线程安全的。无需任何同步即可访问所有共享状态。
所以你真的不能依赖那段代码中的任何东西。