Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-10-09) 阅读数 9 #程序编程
文章标签 Java

在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()方法。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门