public class Constructor_benifit{
public static void main(String[] args){
System.out.println("In primary Thread");
A a=new A("Test string for secondary thread");
Thread thread_object=new Thread(a);
thread_object.start();
}
static class A implements Runnable
{
String to_print;
public A(String to_print){
this.to_print=to_print;
}
public void run(){
System.out.println(to_print);
}
}}
<小时/>
我想在不创建对象的情况下运行此代码...我将 A 类静态化以在没有对象的情况下调用它,但仍然不知道如何调用它。 这段代码工作正常。我只是想知道是否还有其他方法可以以简单的方式执行此代码?
最佳答案
不,您无法在不创建对象的情况下启动线程。
通过实现 Runnable,您应该重写此方法:
public void run(){
并且该方法已在 Runnable 接口(interface)中定义为 virtual(非静态)。
如果你想创建一个线程而不实现Runnable接口(interface),那么你应该扩展Thread类。它不提供启动和运行线程的静态方法。您将再次需要创建 A 类的实例。
如果您只是需要避免额外的对象创建,您可以使用此代码。 我们再次创建对象。但只是一个对象而不是两个。
public class Constructor_benifit{
public static void main(String[] args){
System.out.println("In primary Thread");
Thread thread_object=new A("Test string for secondary thread");
thread_object.start();
}
static class A extends Thread
{
private String to_print;
public A(String to_print){
this.to_print=to_print;
}
public void run(){
System.out.println(to_print);
}
}
}
关于java - 我想运行此代码而不创建类(对象)的实例。是否可以?为什么不?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54126971/