1

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

问候!

主要的

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);
  }
}
4

2 回答 2

6

您继承的类实际上在单独的线程中运行的,但是您的 currentThread 调试是在 main 方法的线程中完成的,而不是 Runnable ClassA 实例。ClassA 实例是在线程本身实际启动之前构造的(因此调用了 Common 构造函数),因此在构造函数中调用 Thread.currentThread() 时,它仍然是主线程。

要修复调试以打印预期结果,您可以将 Common 的构造函数的主体移动到 Common 或 ClassA 中的覆盖 run() 方法(只要它仍然是调用的 run() 方法,由多态性决定)。

于 2012-07-13T06:51:27.663 回答
0

只有run()方法体将在不同的线程中执行。并且,仅当您调用Thread.start(). 其余的,构造函数和其他方法,将在当前线程中执行。

您可以使用匿名类实现在新线程中调用构造函数Runnable

new Thread(new Runnable(){
    new ClassA(country, category, false, false);
}).start();
于 2012-07-13T06:54:08.570 回答