温馨提示×

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

小亿
83
2023-11-22 22:13:48
栏目: 编程语言

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

0