繁体   English   中英

在Java中使用可运行接口实现线程

[英]implementing thread using runnable interface in java

为什么我们必须创建一个类的实例并将其附加到新创建的线程对象,即使它们都在同一类中?

import java.io.*;
class thread1 implements Runnable{

   public void run(){
       System.out.println("thread started");
   }

   public static void main(String args[]) throws Exception{
      Thread t1=new Thread(new thread1());
      t1.start();
   }
}

您无需创建Runnable即可在新线程中执行自定义代码。 也可以直接创建线程的子类。

public class WorkerThread extends Thread{

    @Override
    public void run() {
        // TODO Auto-generated method stub
        super.run();
        // DO SOMETHING
    }

}

public class MainClass {
    public static void main(String[] args){
        new WorkerThread().start();

        MainClass mc = new MainClass();
        mc.startThread();
    }

    private void startThread(){
        Thread t = new WorkerThread();
        t.start();
    }
}

我认为您有两个问题:

1.)如何在Java中使用线程? Fizer Khan的答案就是一个例子。

2.)静态方法如何在Java中工作? 如果您拥有静态方法,那么从某种意义上说,您就位于“静态层”上。 您没有“ this”引用,因为此层上没有对象。 只有创建实例后,您才能访问该对象的实例字段和非静态方法。 如果添加第二个静态方法,则可以执行与主方法相同的操作,因为两者都是静态的。 这是对这个问题的初步看法: https ://stackoverflow.com/questions/18402564/how-do-static-methods-work

pulblic class Thread1 implements Runnable{ //name should be upper case

public void run(){
    System.out.println("thread started");
}

public static void main(String args[]) throws Exception{ //static method
   Thread t1=new Thread(new Thread1()); //t1 is a local reference to an object on the heap - no specil magic here
   t1.start(); //call to an "instance" method, can only be performed on an object.
}

有两种写线程的方法。

public class ThreadX implements Runnable {
    public void run() {
        //Code
    }
}
/* with a "new Thread(new ThreadX()).start()" call */


public class ThreadY extends Thread {
    public ThreadY() {
        super("ThreadY");
    }
    public void run() {
        //Code
    }
}
/* with a "new ThreadY().start()" call */

public class MainClass {
    private Thread threadX = new Thread(new ThreadX());
    private Thread threadY = new ThreadY();

    public static void main(String[] args){
        // Call threads
        threadX.start();
        threadY.start();

        // some more threads
        new Thread(new ThreadX()).start();
        new ThreadY().start();
    }
}

扩展线程时,通常会扩展一个类以添加或修改功能。 因此,如果您不想覆盖任何线程行为,请使用Runnable。

暂无
暂无

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

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