java - 了解线程

标签 java multithreading

我正在尝试弄清楚如何从我的 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/

相关文章:

multithreading - 我如何将 worker 返回到 Go 中的 worker 池

java - 如何使用camel "direct-vm"在两个camel上下文之间进行通信?

java - 从java中创建的球数组制作2个新的球数组

java - 坑突变 - if ( x !=null ) return null else throw new RuntimeException

c# - 为什么 Process.WaitForExit 会阻塞,即使我将它放在单独的线程中?

java - 锁定两种方法但允许一种方法运行多线程

java - Java 中的 Unicode 转义语法

java - Spring Boot编码过滤器

java - LWJGL 错误 - 无法找到 GL 函数 glVertexArrayVertexAttribDivisorEXT 的地址

python - 如何让父线程等待指定的时间或直到子线程完成?