简体   繁体   English

理解线程的java代码

[英]understanding java code for thread

I was just reviewing some java code and I came across the below program 我刚刚查看了一些java代码,我遇到了以下程序

public class LengthOfString extends Thread {
    static String s;

    public void run(){
        System.out.println("You Have Enter String: " + s +"  Length Of It is :" + s.length());
    }

    public static void main(String[] args) throws InterruptedException {
        s = "This IS String";
        LengthOfString h = new LengthOfString(); //creating the object of class
        Thread t = new Thread(h);   //why we have passed this object here???
        t.start();
    }
} 

I understood that it is used to print string length, but I have a problem understanding the commented line. 我知道它用于打印字符串长度,但我在理解注释行时遇到问题。 Please help me to understand why this implementation was used. 请帮助我理解为什么使用这个实现。

Actually in java, there are 2 ways to create a Thread . 实际上在java中,有两种方法可以创建一个Thread

  • Provide a Runnable object. 提供Runnable对象。 The Runnable interface defines a single method, run, meant to contain the code executed in the thread. Runnable接口定义了一个run方法,用于包含线程中执行的代码。 The Runnable object is passed to the Thread constructor. Runnable对象被传递给Thread构造函数。

  • Subclass Thread. 子类线程。 The Thread class itself implements Runnable, though its run method does nothing. Thread类本身实现了Runnable,尽管它的run方法什么都不做。 An application can subclass Thread, providing its own implementation of run. 应用程序可以子类化Thread,提供自己的run实现。

You chosen the second one and you can simply write 你选择了第二个,你可以简单地写

new LengthOfString().start();

instead 代替

LengthOfString h=new LengthOfString(); //creating the object of class

Thread t=new Thread(h);   //why we have passed this object here???

 t.start();

Edit: 编辑:

Thread class have a constructor public Thread(Runnable target) , that it takes Runnable type as a parameter and when you pass that to thread class it calls the implementation of run() method when you start that thread. Thread类有一个构造函数public Thread(Runnable target) ,它将Runnable类型作为参数,当你将它传递给线程类时,它会在你启动该线程时调用run()方法的实现。

In this case, you don't need the Thread t=new Thread(h) line, because LengthOfString extends Thread. 在这种情况下,您不需要Thread t = new Thread(h)行,因为LengthOfString扩展了Thread。 Many times though, you implement the Runnable Interface. 但很多时候,您实现了Runnable接口。 In that case, you need to create a Thread object with a Runnable argument in the constructor, because Runnable Objects dont have a start methods 在这种情况下,您需要在构造函数中创建一个带有Runnable参数的Thread对象,因为Runnable Objects没有启动方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM