java中怎么通过thread类创建线程

40次阅读
没有评论

共计 893 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,有两种常见的方法可以通过 Thread 类创建线程。

第一种方法是继承 Thread 类,重写其 run() 方法。具体步骤如下:

  1. 创建一个继承自 Thread 类的子类,并重写 run() 方法。
public class MyThread extends Thread {@Override
    public void run() {// 线程执行的代码 
        System.out.println("Hello, World!");
    }
}
  1. 创建 Thread 子类的对象,并调用 start() 方法启动线程。
public class Main {public static void main(String[] args) {MyThread myThread = new MyThread();
        myThread.start();}
}

第二种方法是实现 Runnable 接口,重写其 run() 方法。具体步骤如下:

  1. 创建一个实现 Runnable 接口的类,并重写 run() 方法。
public class MyRunnable implements Runnable {@Override
    public void run() {// 线程执行的代码 
        System.out.println("Hello, World!");
    }
}
  1. 创建 Runnable 实现类的对象。
public class Main {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();}
}
  1. 创建 Thread 对象,将 Runnable 实现类的对象作为参数传递给 Thread 的构造方法。
public class Main {public static void main(String[] args) {MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();}
}

无论是继承 Thread 类还是实现 Runnable 接口,线程的执行代码都写在 run() 方法中。调用 start() 方法会启动线程,并自动调用 run() 方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-09发表,共计893字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)