线程扩展,访问方法与提交的值
因此,我正在尝试编写一个简单的类,该类正在扩展线程类。 我将非常感激
在写它的同时,我发现了一个有趣而令人困惑的伤亡,如果有人解释了我为什么确实有效的话,
@Override
public void run(){
startTime = System.currentTimeMillis();
running = true;
while (isRunning()) {}
}
:但是,
@Override
public void run(){
startTime = System.currentTimeMillis();
running = true;
while (running) {}
}
使用覆盖的方法:
@Override
public void interrupt(){
running = false;
Long endTime = System.currentTimeMillis();
int time = Math.round(endTime - startTime);
out.println(time);
}
btw isrunning()
只是一个简单的getter女巫返回 运行
的布尔值。
So I am trying to write a simple class that is extending Thread class. While writing it I found a funny and confusing casualty and I would be very grateful if someone explain me
why this code does work:
@Override
public void run(){
startTime = System.currentTimeMillis();
running = true;
while (isRunning()) {}
}
but this code doesn't:
@Override
public void run(){
startTime = System.currentTimeMillis();
running = true;
while (running) {}
}
with overridden interrupt method:
@Override
public void interrupt(){
running = false;
Long endTime = System.currentTimeMillis();
int time = Math.round(endTime - startTime);
out.println(time);
}
BTW isRunning()
is just a simple getter witch returns boolean value of running
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在这里拥有的是 种族条件 。在Java的特殊情况下,我们可以从 JLS
您有一个变量,并且有两个线程同时访问它,其中其中一个线程正在写入其中。要保护此数据,您需要 synchronize 两次访问。通常,建议在类型
对象
的私有实例变量上同步,以便没有其他人对该变量进行引用。 (同步
方法的默认行为是在this
上同步,如果有参考此同步的其他人,它可能会引起问题同样),
而且,正如评论中已经指出的那样,当您做这样的事情时,通常会皱眉
thread
。考虑在Runnable
子类中制作Run()
,然后只需使用thread
构造函数即可。What you have here is a race condition. In the particular case of Java, we can read a direct definition from the JLS
You have a single variable and you have two threads accessing it at the same time, where one of those threads is writing to it. To protect this data, you need to synchronize both accesses. Generally, it's advised to synchronize on a private instance variable of type
Object
, so that no one else has a reference to that variable. (The default behavior ofsynchronized
methods is to synchronize onthis
, which can cause problems if someone else who has a reference tothis
synchronizes on it as well)And, as has already been pointed out in the comments, it is generally frowned upon to subclass
Thread
when you're doing things like this. Consider making yourrun()
in aRunnable
subclass and simply use theThread
constructor.