这是我正在使用的一段代码,作为如何运行多个线程的示例:
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);
}
}
我或多或少只是从runnable上的文档中获取它。但是我发现很难理解为什么它会像这样工作。我还是OOP的新手并且我真的不明白我如何实例化一个接口(runnable),如果我的runnable对象不是一个类,我怎么能定义它一个方法(run())...可以某人请用简单的语言逐步向我解释一下构造函数中发生了什么,这样我才能理解这个过程?三江源!
答案 0 :(得分:0)
您创建的内容称为Anonimous class。该链接包含解释它是什么的官方教程,但简而言之 - 您创建了一个实现Runnable
的一次性类,并实例化了该类的对象。
作为一个建议 - 在掌握OOP和语法等语言的基本概念之前,不要试图解决多线程问题。
答案 1 :(得分:0)
在Java接口中无法实例化,它们只是方法必须实现的指南才能实现该接口。为了在Java中实例化一个线程,最好使用
public class ThreadDem extends Runnable
(推荐)
或
public class ThreadDem extends Thread
。
此时您需要实施"公共无效运行"从Runnable覆盖空的方法。此时,您只需在ThreadDem类型的任何对象上调用run。