作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我现在的代码,不幸的是,继承的类没有在单独的线程中运行,我希望继承的类在单独的线程中运行。请告诉我这样做的最佳方法是什么。
问候!
主要
public class Main
{
public static void main(String[] args)
{
new Thread(new ClassA(country, category, false, false)).start();
}
}
A 级
ClassA extends Common implements Runnable
{
volatile String country;
volatile String category;
volatile Boolean doNotReset;
volatile Boolean doNotFlash;
public ClassA(String country, String category, Boolean doNotReset, Boolean doNotFlash)
{
this.country = country;
this.category = category;
this.doNotReset = doNotReset;
this.doNotFlash = doNotFlash;
}
@Override
public void run()
{
}
}
常见
public class Common
{
Common()
{
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println("name=" + name);
}
}
最佳答案
您的继承类实际上是在单独的线程中运行,但是您的currentThread 调试是在main 方法的线程中完成的,而不是在Runnable ClassA 实例中完成的。 ClassA 实例是在线程本身实际启动之前构造的(因此调用了 Common 构造函数),因此在构造函数中调用 Thread.currentThread() 时,它仍然是主线程。
要修复调试以打印预期结果,您可以将 Common 的构造函数的主体移动到 Common 或 ClassA 中覆盖的 run() 方法(只要它仍然是调用的 run() 方法,由多态性决定).
关于java - 多线程和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11465453/
我是一名优秀的程序员,十分优秀!