有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建多线程并实例化runnable

这是我正在使用的一段代码,作为如何运行多线程的示例:

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())。。。有人能用简单的术语一步一步地向我解释这个构造函数中到底发生了什么,这样我才能理解这个过程吗?谢谢


共 (2) 个答案

  1. # 1 楼答案

    在Java中,接口不能被实例化,它们只是一个方法必须实现什么才能实现该接口的指南。为了在Java中实例化线程,最好使用

    public class ThreadDem extends Runnable(推荐)

    或者

    public class ThreadDem extends Thread

    此时,您需要实现一个“public void run”方法,从Runnable覆盖空的方法。此时,您只需在任何类型的ThreadDem对象上调用run

  2. # 2 楼答案

    你所创造的被称为Anonimous class。该链接包含解释它是什么的官方教程,但简而言之,您创建了一个实现Runnable的一次性类,并实例化了该类的一个对象

    作为建议——在掌握OOP和语法等语言的基本概念之前,不要尝试处理多线程