java如何创建多线程

avatar
作者
猴君
阅读量:0

在Java中,可以通过以下方式创建多线程:

  1. 继承Thread类:创建一个新的类并继承Thread类,重写run()方法来定义线程执行的任务。然后创建该类的对象并调用start()方法启动线程。
public class MyThread extends Thread {     public void run() {         // 线程执行的任务     } }  public class Main {     public static void main(String[] args) {         MyThread thread = new MyThread();         thread.start();     } } 
  1. 实现Runnable接口:创建一个实现了Runnable接口的类,实现run()方法来定义线程执行的任务。然后创建该类的对象,并将其作为参数传递给Thread类的构造方法,最后调用start()方法启动线程。
public class MyRunnable implements Runnable {     public void run() {         // 线程执行的任务     } }  public class Main {     public static void main(String[] args) {         MyRunnable myRunnable = new MyRunnable();         Thread thread = new Thread(myRunnable);         thread.start();     } } 
  1. 使用匿名内部类:可以直接在创建Thread对象时使用匿名内部类来实现线程执行的任务。
public class Main {     public static void main(String[] args) {         Thread thread = new Thread(() -> {             // 线程执行的任务         });         thread.start();     } } 

无论采用哪种方式,创建多线程后,可以通过调用start()方法启动线程,并在run()方法中定义线程执行的任务。