这是我用作如何运行多个线程的示例的一段代码:
import javax.swing.SwingUtilities;
public class ThreadDem {
//field
Runnable doRun;
//constructor
public ThreadDem(){
//instantiates a runnable object
doRun = new Runnable(){
//have to override the abstract method run of runnable and am
//declaring method here in this block statement
@Override
public void run() {
System.out.println("Hello from thread: "
+ Thread.currentThread());
}
};
}
public static void main (String[] args){
ThreadDem demo = new ThreadDem();
System.out.println("Hello this is from thread: " +
Thread.currentThread());
//I use the invokelater method to invoke the run method of do run on a
//seperate thread
SwingUtilities.invokeLater(demo.doRun);
}
}
我或多或少只是从可运行的文档中获取了它。但是我发现很难理解为什么它会这样工作。我对 OOP 还很陌生,并不真正理解如何实例化一个接口(interface)(可运行),如果我的可运行对象确实不是一个类,我如何将它定义为一个方法(run())...有人可以解释一下吗对我来说,简单来说,构造函数中到底发生了什么,以便我能够理解这个过程?谢谢!
最佳答案
您创建的内容称为 Anonimous class 。该链接包含解释它是什么的官方教程,但简而言之 - 您创建了一个实现 Runnable 的一次性类,并实例化了该类的一个对象。
作为建议 - 在掌握语言的基本概念(例如 OOP 和语法)之前,不要尝试解决多线程问题。
关于java - 创建多线程并实例化可运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23959260/