public class MyRunnableTask implements Runnable {
public void run() {
// do stuff here
}
}
是否可以仅使用类名来启动上述类的线程?
更新:
我按照@zhh的评论进行了尝试,并且成功了。我们需要使用反射创建一个类的对象
示例代码:
public class Runner2 implements Runnable {
volatile int count =0;
public void run() {
System.out.println("Inside runner 2 -"+LocalTime.now());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void shutdown() {
System.out.println("shuutting down");
}
}
public class Test_thread {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
Class<?> myclass = Class.forName("Runner2");
Constructor<?> constructor = myclass.getConstructor();
System.out.println(myclass);
Object obj=constructor.newInstance(new Object[] {});
Runnable run = (Runnable)obj;
Thread t = new Thread(run);
t.start();
Method m = myclass.getMethod("shutdown");
m.invoke(obj);
}
}