java - 多线程和继承

标签 java multithreading

这是我现在的代码,不幸的是,继承的类没有在单独的线程中运行,我希望继承的类在单独的线程中运行。请告诉我这样做的最佳方法是什么。

问候!

主要

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/

相关文章:

c# - 如何在 C# 中对二进制 MIME 附件进行编码?

c++ - C++中Concurrent Queue + map的实现

php - 如何在php中使用多线程

java - 多线程问题

java - spring boot 在 json 响应中包含 OneToMany 关联

java - 创建一个以 JsonObject 为键的 HashMap

java - spring-el线程中的SpelExpression安全吗?

c# - 在 C# 中监视变量

c# - 即使使用多线程,用户界面仍然锁定

Java在synchronized block 中调用其他方法