我正在尝试弄清楚如何从我的 public static void main 运行 NamedRunnable。 我本质上是在试验两种运行线程的方法,第一种是创建并定义线程,第二种是定义一个类,然后实现可运行的。
这是我的代码
package threads;
public class Threads extends Thread{
private final String name; // The name of this thread
public static void main(String[] args) {
long lStartTime = System.nanoTime();
Threads greetings = new Threads("Fred");
Threads greetings1 = new Threads("Betty");
NamedRunnable greetings2 = new NamedRunnable("Ralph");//it is here i cant seem to create an instance of Named Runnable and therefore call start
greetings.start();
greetings1.start();
greetings2.start();
long lEndTime = System.nanoTime();
long difference = lEndTime - lStartTime;
System.out.println("Elapsed time: " + difference);
}
public Threads(String name) {
this.name = name;
}
public void run() { // The run method prints a message to standard output.
System.out.println("Greetings from thread ’" + name + "’!");
}
public class NamedRunnable implements Runnable {
private final String name;
// The name of this Runnable.
public NamedRunnable(String name) { // Constructor gives name to object.
this.name = name; }
public void run() { // The run method prints a message to standard output.
System.out.println("Greetings from runnable ’" + name +"’!"); } }
}
最佳答案
Thread 和 Runnable 是两个不同的东西:
线程是映射到操作系统线程的对象。在线程上调用 start 会分配并执行一个线程。
Runnable 描述了要执行的任务。
线程只是执行 Runnable 的一种方式。您可以使用线程来运行 Runnable,如
Runnable myRunnable = new Runnable() {
public void run() {
System.out.println("Hello");
}
};
new Thread(myRunnable).start();
或者您可以将 Runnable 提交给 ExecutorService 并让服务决定如何执行它:
executorService.submit(myRunnable);
或者你可以在当前线程中执行Runnable:
myRunnable.run();
为了方便起见,有人决定让 Thread 实现 Runnable,这样他们就可以用稍微更少的代码编写演示。
关于java - 了解线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406236/