gpt4 book ai didi

java - 多线程和继承

转载 作者:行者123 更新时间:2023-11-29 07:13:51 27 4
gpt4 key购买 nike

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

问候!

主要

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com