简体   繁体   English

使用Runnable和Thread创建线程的区别?

[英]Difference in creation of thread using Runnable and Thread?

This code is working fine but if I use the constructor Thread(name) in 6th line instead of Thread(this,name) it is not working I just want to know what makes the difference? 这段代码工作正常,但是如果我在第6行中使用构造函数Thread(name)而不是Thread(this,name),则它无法正常工作,我只是想知道有什么区别?

public class threadtest implements Runnable{
    Thread t;

    public threadtest(String name)
    {
        System.out.println("satheesh");
        Thread t=new Thread(this,name);
        t.start();
        t=null;
        //System.out.println(this+"\n"+t);
    }

    public void run(){
        System.out.println("satheesh");
        for(int i=0;i<=10;i++)
        {
            try{
                System.out.println("satheesh");
                Thread.sleep(1000);
                System.out.print(Thread.currentThread());
            }
            catch(Exception e)
            {
                System.out.println(e);
            }
        }
    }

    public static void main(String args[])
    {
        threadtest ob=new threadtest("satheesh");       
    }
}

There's two ways to create a thread: 有两种创建线程的方法:

  1. Subclass Thread , override run , and then create an instance of your subclass 子类Thread ,重写run ,然后创建您的子类的实例

  2. Extend Runnable and give it to a thread to "run" it 扩展Runnable并将其提供给线程以“运行”它

Your code does #2 - you implemented Runnable , so you must give it to a thread to "run" it. 您的代码执行#2-实现了Runnable ,因此必须将其提供给线程以“运行”它。

if I use the constructor Thread(name) in 6th line instead of Thread(this,name) it is not working I just want to know what makes the difference? 如果我在第6行中使用构造函数Thread(name)而不是Thread(this,name) ,则它不起作用,我只是想知道有什么区别?

The difference is that: 区别在于:

  • Thread t= new Thread(this,name);

    Creates a new thread that is given your Runnable ( this ) to run when it is started. 创建一个新线程,让您的Runnablethis )在启动时运行。

  • Thread t= new Thread(name);

    Creates a new thread is not given any Runnable to run. 创建一个新线程没有任何Runnable来运行。 So the thread does nothing when it is started. 因此,线程在启动时不执行任何操作。

Writing new Thread("somename") creates a thread that won't do anything. 编写new Thread("somename")会创建一个不会执行任何操作的线程。
(since you never provided anything for it to run) (因为您从未提供运行所需的任何内容)

我们使用runnable接口创建线程,如果我们使用runnable接口,则在线程构造函数中,我们传递runnable对象引用和线程名称。当您使用thread(name)时,它不称为start(),但是当您创建thread(this时,名称),它满足了可运行线程的需求并启动了start()。

There's a simple (and understandable) misunderstanding of what the different Thread constructors do. 对于不同的Thread构造函数有一个简单的(可以理解的)误解。 There are two constructors in question: 有两个有问题的构造函数:

  1. Thread(Runnable, String) creates a Thread , assigns its name to the String and specifies that it should run the Runnable . Thread(Runnable,String)创建一个Thread ,将其名称分配给String并指定它应运行Runnable

  2. Thread(String) calls the general constructor with special magic arguments of Thread (null, null, name) . Thread(String)使用Thread的特殊魔术参数(null,null,name)调用常规构造函数。 This creates a new Thread but it will run the method in the Thread , not any provided Runnable . 这将创建一个新的Thread ,但它会在运行的方法Thread ,没有提供任何Runnable As a result, if you call t.start() , it's going to call the Thread's run() method. 结果,如果您调用t.start() ,它将调用线程的run()方法。

So, a simple rewrite of the code gets you what you want: 因此,简单地重写代码即可获得所需的内容:

public class threadtest extends Thread { // [sic] on the capitalization

    public threadtest(String name) {
        System.out.println("satheesh");
    }

    public void run() {
        System.out.println("satheesh");
        for(int i=0;i<=10;i++) {
        try {
            System.out.println("satheesh");
            Thread.sleep(1000);
            System.out.print(Thread.currentThread());
        } catch(Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String args[]) {
        threadtest ob = new threadtest("satheesh");
        // The following will call the correct run method now
        ob.start();
    }

}

1st, we should knew Thread(String s) vs Thread(Runnable r, String s) different purpose. 首先,我们应该知道Thread(String s)与Thread(Runnable r,String s)的不同用途。

The different is Thread(String s) we sent "value" in bracket () to constructor that implements Runnable but Thread(Runnable r, String s) we give a thread name to String s to the thread constructor that implements Runnable. 区别在于Thread(String s) 我们将括号()中的“值”发送给实现Runnable的构造函数,而Thread(Runnable r,String s) 我们将String的线程名称赋予实现Runnable的线程构造函数。

Here the same code that implements Runnable via Thread (Runnable r, String s). 这里是通过线程实现Runnable的相同代码(Runnable r,String s)。

public class threadtest implements Runnable{
Thread t;
threadtest th;

public threadtest(){}

public threadtest(String name)
{
System.out.println("satheesh");
Thread t=new Thread(th, name); //satheesh,name of thread, gave to name
t.start(); //2nd thread that will start run() method in void run()
//t=null;
//System.out.println(this+"\n"+t);
}
public void run(){
 System.out.println("satheesh");
for(int i=0;i<=10;i++)
{
try{
System.out.println("satheesh");
Thread.sleep(1000);
System.out.print(Thread.currentThread());
}
catch(Exception e)  { System.out.println(e); }
}
}
public static void main(String args[]){

//ob is Runnable object that will send his empty value ()
threadtest ob = new threadtest(); //to default constructor threadtest() above

//satheesh is name of main thread that we will send to String name in Thread t=new Thread(th, name);
Thread th = new Thread(ob, "satheesh");
th.start();  //1st thread that will instruct to send satheesh
}
}

output: 输出:

satheesh
satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
Thread[satheesh,5,main]satheesh
BUILD SUCCESSFUL (total time: 11 seconds)

Your question is the same as this question: "implements Runnable" vs. "extends Thread" 您的问题与以下问题相同: “可运行的实现”与“扩展线程”

Another good source of information is this thread on coderanch.com http://www.coderanch.com/t/233370/threads/java/Thread-vs-Runnable 另一个好的信息来源是coderanch.com http://www.coderanch.com/t/233370/threads/java/Thread-vs-Runnable上的该线程

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

相关问题 在Java中使用notify时,线程和可运行之间有什么区别吗? - Is there any difference between thread and runnable when using notify in Java? 在使用Runnable的线程和派生的Thread类之间发生行为方面的意外差异 - Unexpected difference in behaviour between using a thread using a Runnable and a derived Thread class 线程和Runnable - Thread and Runnable 运行线程和可运行线程 - Running a Thread and Runnable Thread ThreadPool中的Runnable与Thread和ThreadPool中的Runnable有什么区别 - What is Difference between Runnable in a ThreadPool vs Runnable inside a Thread and in a ThreadPool 如何在主线程下拦截 Runnable 创建和执行以使用 AspectJ 填充上下文流数据 - How to intercept Runnable creation and execution under master thread to populate context flow data using AspectJ Java Multithreading:如何使用Runnable接口创建线程? - Java Multithreading : how does thread creation with Runnable interface work? 如何在ThreadFactory中创建线程期间访问Runnable? - How to access Runnable during Thread creation inside ThreadFactory? new Thread(Runnable object).start() 与 new Thread(Runnable ref. {run()});.start() 之间的区别 - DIfference between new Thread(Runnable object).start() vs. new Thread(Runnable ref. {run()});.start() 使用Runnable或Thread出现Java线程问题 - Issue with Java threads, using Runnable or Thread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM